React - useContext() is returning "undefined"

30 Views Asked by At

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".

2

There are 2 best solutions below

0
Mr. Terminix On

When you are consuming the context, you are receiving the variable which is passed in value. In your case you have:

<BrandContext.Provider value={{imgSrc: logo}}>{children}</BrandContext.Provider>

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.

0
Xin Yi On

Did you wrap your BrandComponent.jsx within the Context Provider?

If you didn't wrap the BrandComponent.jsx within the Context Provider, it will return undefined.

<div className='App'>
  <ContextProvider>
    <BrandComponent customWidth={10} customHeight={10} />
  </ContextProvider>
</div>

This is how you should wrap your BrandComponent within ContextProvider.