skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search