0

I am trying to use useContext in react and I have a problem sending value into the provider but in useContext I can not get this value

make createContext in parent "index"

export const multiLanguageContext = React.createContext ();
export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={(<> 
            <NavBar/> 
            <Outlet/>
            </>
        )}>

use provider in navbar

function NavBar(props) {
   const[language,setLanguage]=React.useState(Data_multi_language.english);
  return (
    <>
    <multiLanguageContext.Provider value={{language}}>

and use useContext in fn1

function fn1() {
  const [language] = useContext(multiLanguageContext)
    return (
      <>
        <div className="div_of_about_us">
        <Empety/>
          <h1 className="style_of_text_about_me">
            {language.text1_navbar_aboutMe}<span className="style_of_text_me_about_me"> Me.</span>
          </h1>
amirSh2010
  • 23
  • 3
  • Is `fn1` supposed to be a React component? And if so, it should be Capitalized and is it rendered within the ReactTree created by the `NavBar` component? https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese Apr 05 '22 at 07:37

1 Answers1

0

What is the type/shape of the context value?

// Looks like you are expecting an array. But are you?
// I think you context value is an object, right?

const [language] = useContext(multiLanguageContext)

See if it helps.

const LangContext = React.createContext(null);

const Child = () => {
  const { language } = React.useContext(LangContext);
  return(
    <div>
      From Child. Language: { language }
    </div>
  );
}

const App = () => {

  const contextValue = { language: 'EN' };

  return(
    <LangContext.Provider value={contextValue}>
      <Child/>
    </LangContext.Provider>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336