Home > Software engineering >  How to use context api to pass a prop from layout to children in next js
How to use context api to pass a prop from layout to children in next js

Time:01-10

I am having issues using context api to pass a state globally in my app Layout. I have this Layout component.

import { useState, useEffect,createContext } from 'react'
import useAPIStore from "../store/store";
import React from 'react';
export const userContext = createContext();  
const Layout = ({ children }: Props) => {
  const [selected, setSelected] = useState(countries[0]);
  console.log("The country idsz ...........",selected.id)
  const country= selected.id
  return (
    <>
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      <userContext.Provider value={country}>
      {children}
      </userContext.Provider>
     </LayoutContent>
    </>
  )
}
export default Layout;

I am passing the country value to the children of the layout using the context provider.This is how I am accessing it in one of the child components

import React ,{useContext} from 'react'
import Layout from '../components/layout'
import { userContext } from '../components/layout'
const ComingSoonCarbon = () => {
  const value = useContext(userContext)
  console.log("mamamamia",value)
  return (
    <Layout>
    <div className="flex justify-center font-bold mt-80 text-xl text-[rgb(245,132,38,0.93)]">
      <h1>{value}</h1>
      </div>
    </Layout>
  )
}

export default ComingSoonCarbon

I am getting an undefined value from value , what might be the problem ? Someone help me out.I am stuck.

CodePudding user response:

export const userContext = createContext({country: "Sudan"})

You need to Move the COntext Out Of The Component Dir if you want all components to have access to the context provider .

CodePudding user response:

For react function components the function name must be in UpperCamelCase.

Rename the userContext to UserContext.

import { useState, useEffect,createContext } from 'react'
import useAPIStore from "../store/store";
import React from 'react';
export const UserContext = createContext("");  
const Layout = ({ children }: Props) => {
  const [selected, setSelected] = useState(countries[0]);
  console.log("The country idsz ...........",selected.id)
  const country= selected.id
  return (
    <>
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      <UserContext.Provider value={country}>
      {children}
      </UserContext.Provider>
     </LayoutContent>
    </>
  )
}
export default Layout;
  • Related