1

I have declared a React context in indexa.js and I'm trying to access the context value set in App.js in Employee.js. But it's not rendering the value I'm new to React. Please help me out. Thanks in advance

//index.js

export const employeeContext = React.createContext();
const AppContextInteration = <App></App>
ReactDOM.render(AppContextInteration, document.getElementById('root'));

//App.js

export class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            EmpId: 1,
            EmpName: 'xxx'
        }
    }

    render() {
        return (
            <div>
                <h1> App Component</h1>
                <p> Employee Id : {this.state.EmpId}</p>
                <employeeContext.Provider value={this.state} >
                     <Employee/>
                </employeeContext.Provider>

            </div>
        )
    }
}
//Employee.js

export class Employee extends React.Component {
    context = employeeContext;
    constructor(props) {
        super(props);
        console.log();
    }
    render() {
        return (
            <div>
                <h1>Employee Component </h1>
                <p> Employee Id  : {this.context.EmpId} </p>
            </div>
        )
    }
}

2 Answers2

0

you can use Context.Consumer

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

https://reactjs.org/docs/context.html

I prefer using functional component with useContext hook (this is very easy to implement) you may refer React hooks tutorial(useContext)

SathwikaRao
  • 133
  • 1
  • 8
0

As you said you are new to react, still you have worked so well almost.This error occurs may be you haven't import context(employeeContext) in your employee component, if you already imported then i suggest you to use convert it into function component and use (useContext) hook that would be much better, performance and understanding wise. Thanks

link: https://www.youtube.com/watch?v=UjjtvroahBU&list=PLC3y8-rFHvwisvxhZ135pogtX7_Oe3Q3A&index=17&ab_channel=Codevolution