Search code examples
javascriptreactjsreact-context

How to handle multiple contexts using react-context-api into child also in react?


I am using a context definition in the app and the same component to create a child component to pass the parent value from parent to child component. So here in the same level, it's working fine, but the same parent value passes to the child component. But here, I want the same value that prints in the parent to show in the child, and I also got an error "Cannot read properties of undefined (reading '_context')" ,so what changes should I make in that component?

import React, { useContext } from "react";
import DropDown from "./DropDown";

const UserContext = React.createContext();
const CartContext = React.createContext();
function MyComponent() {
  const user = useContext(UserContext);
  const cart = useContext(CartContext);

  return (
    <div>
      <h1>Hello, {user.name}!</h1>
      <h2>You have {cart.items.length} items in your cart.</h2>
    </div>
  );
}
function App() {
  return (
    <UserContext.Provider value={{ name: "John" }}>
      <CartContext.Provider value={{ items: ["Apple", "Banana"] }}>
        <MyComponent />
        <DropDown />
      </CartContext.Provider>
    </UserContext.Provider>
  );
}

export default App;

child component also given

import React, { useContext } from "react";
import { UserContext, CartContext } from "./App";
export default function DropDown() {
  const userValue = useContext(UserContext);
  const cartValue = useContext(CartContext);
  console.log(userValue, cartValue);

  return (
    <>
      <h1>{userValue}</h1>
      <p>{cartValue}</p>
    </>
  );
}

Solution

  • First you have forgotten to export the Contexts from App.js:

    // ...
    export const UserContext = React.createContext();
    export const CartContext = React.createContext();
    // ...
    

    Then also React doesn't know how to render Objects and it will throw you an error, so modify your DropDown component:

    import React, { useContext } from "react";
    import { UserContext, CartContext } from "./App";
    export default function DropDown() {
      const userValue = useContext(UserContext);
      const cartValue = useContext(CartContext);
      console.log('userValue:', userValue, 'cartValue:', cartValue);
    
      return (
        <>
          <h1>Name: {userValue.name}</h1>
          {cartValue.items.map(item => <p>Item: {item}</p>)}
        </>
      );
    }