Search code examples
reactjsreact-contextreact-16

The react context from the child does not change


I read the solution from a similar question but it did not help.
Here is my simple code: https://codesandbox.io/s/gracious-jennings-ugqzd


import myContext from "./myContext";
import Two from "./Two.js";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: 0
    };
  }

  render() {
    return (
      <myContext.Provider value={this.state}>
        <div className="App">
          <Two />
          <h2>{this.state.number}</h2>
        </div>
      </myContext.Provider>
    );
  }
}

export default App;

I need to set it up so it could be anywhere in class <Two /> change the variable number. Help is appreciated thanks.


Solution

  • You can't just mutate state so

      componentDidMount() {
        this.context.number = 100;
      }
    

    If you mutate state react doesn't re render because you mutated it. You can do the following:

    In App:

    import React from "react";
    import "./styles.css";
    import myContext from "./myContext";
    import Two from "./Two.js";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          number: 0
        };
      }
      increase = ()=> this.setState({number:this.state.number+1})
    
      render() {
        return (
          <myContext.Provider value={{...this.state,increase:this.increase}}>
            <div className="App">
              <Two />
              <h2>{this.state.number}</h2>
            </div>
          </myContext.Provider>
        );
      }
    }
    
    export default App;
    

    In Two:

    import React from "react";
    
    import myContext from "./myContext";
    
    class Two extends React.Component {
      static contextType = myContext;
    
      render() {
        return (
          <myContext.Consumer>
            {({ number,increase }) => <h1 onClick={increase}>{number}</h1>}
          </myContext.Consumer>
        );
      }
    }
    
    export default Two;