I created a ContextProvider to pass the image to a child component, but it's returning "undefined" for some reason.
Here's my folder structure: enter image description here
Here's my source code for ContextProvider.jsx:
import React, { createContext } from "react";
import logo from "../assets/logo.jpeg";
export const BrandContext = createContext();
export default function ContextProvider({ children }) {
return (
<>
<BrandContext.Provider value={{imgSrc: logo}}>{children}</BrandContext.Provider>
</>
);
}
Here's my source code for BrandComponent.jsx:
import React, { useContext } from "react";
import { BrandContext } from "../../context/ContextProvider";
export default function BrandComponent({
logoImageSrc,
customWidth,
customHeight,
}) {
const brandContext = useContext(BrandContext);
return (
<div className="logo d-flex flex-direction-row custom-width-sm-30 custom-width-md-40 ms-5">
<h1 className="navbar-brand fs-2 custom-font-family-teko custom-color-darkpurple">
Gym
<img
src={brandContext}
alt="gym-bro-logo"
className={`custom-width-${customWidth} custom-height-${customHeight}`}
/>
Bro
</h1>
</div>
);
}
I tried to pass a boolean value (i.e. <BrandContext.Provider value={true}>...) instead, and it still returns "undefined".
When you are consuming the context, you are receiving the variable which is passed in value. In your case you have:
The variable passed to value is an object with a key imgSrc and his value the logo. If you want to consume that value, you have to pass "src={brandContext.imgSrc}".
I want to mention that the file, where the ContextProvider is used is not given. Make sure BrandComponent is a children of the ContextProvider.