PC1509
PC1509

Reputation: 31

value is not passed to child component using context in react

Employee id is not getting reflected for Employee component.

const employeecontext= React.createContext();

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: 101
    };
  }
  render() {
    return (
      <div>
        <h1>welcome to App</h1>
        <p>
          <label> Employee id: {this.state.id}</label>
        </p>
        <employeecontext.Provider value={this.state}>
          <Employee />
        </employeecontext.Provider>
      </div>
    );
  }
}

Employee Class:

class Employee extends React.Component {
  static context = employeecontext;

  render() {
    return (
      <div>
        <h1>welcome to employee</h1>
        <p>
          <label> Employee id: {this.context.id}</label>
        </p>
      </div>
    );
  }
}

Upvotes: 1

Views: 83

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

The problem is just this line:

static context = employeecontext;

Simply use the correct static class property which is contextType.

Like so:

static contextType = employeecontext;

Upvotes: 1

Related Questions