0

Inside of App component I have Component1 which has a nested component. I create a contextApi with React.createContext() to use it inside of nested component . Using useContext() hook I am trying to get myname value from App.js and use it as style, but it returns undefined. App component

      import logo from './logo.svg';
      import './App.css';
      import Component1 from '../src/Component1/Component1'
      import React from 'react'
      export const Theme  = React.createContext();
      function App() {

      const myname = {
       width:'100px',
       height:'100px',
       background:'red'
     }
    return (
<Theme.Provider  value={{myname}}>
  <Component1>
    </Component1> 
</Theme.Provider>

); }

   export default App;

Component1

      import NestedComponent from '../NestedComponent/NestedComponent'
      function Component1 (){
      return <NestedComponent></NestedComponent>
       }
     export default Component1

NestedComponent

import Theme from '../App'
import {useContext} from 'react'
  export default function  NestedComponent(){
    const mystyle  = useContext(Theme)   //returns undefined
    return  <div style = {mystyle}>  </div>

}

Parviz Pirizade
  • 193
  • 2
  • 12
  • You wrapped myname inside an object, so your context is ```{myname: {width: '100px'}}``` so, just do, ```const { myname } = useContext(Theme);``` – Kakiz May 05 '21 at 16:07
  • it gives below error TypeError: Cannot destructure property 'myname' of 'Object(...)(...)' as it is undefined. – Parviz Pirizade May 05 '21 at 16:51

1 Answers1

0

Inside Theme.Provider do this:

<Theme.Provider  value={myname}>

It will work. Check here

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
  • it is still undefined – Parviz Pirizade May 05 '21 at 15:02
  • Theme in my code returns this : App() { const myname = { background: "red", width: "100px", height: "100px" }; return /*#__PURE__*/Object(react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_4__["jsxDEV"])(Theme.Provide… but it should return calculateChangedBits: null, _currentValue: undefined, _currentValue2: undefined, _threadCount: 0, Provider: Object…} _calculateChangedBits: null _currentValue: undefined _currentValue2: undefined _threadCount: 0 Provider: Object Consumer: Object _currentRenderer: Object _currentRenderer2: null – Parviz Pirizade May 05 '21 at 17:06
  • it does not see it as context – Parviz Pirizade May 05 '21 at 17:08
  • hey, I found out the problem when importing Theme it should have been import {Theme} from '../App' but i do not understand why – Parviz Pirizade May 05 '21 at 17:24
  • Because Theme is not a default export from App.js. Only, default exports can be imported without curly braces. – Charchit Kapoor May 06 '21 at 03:13