Mykh Channel
Mykh Channel

Reputation: 3

how to change react state from other file?

I have reactJs files. And I need to use state from first file in second, to change state in first from second file) P.S. i need change (test: false (need-> true)) from class B(other file).

class A extends Component {
  this.state = {
            test: false
        };
}

////////////////
class B extends Component {
  

}

Upvotes: 0

Views: 3257

Answers (1)

Stretch0
Stretch0

Reputation: 9251

Either use redux, or handle the state in the parent component and pass it down like so:

class A extends Component {
  // ...
}


class B extends Component {

  updateTestInB(){
    this.props.updateTest(true)
  }

}

class Parent extends Component {

    state = {
        test: false
    }

    updateTest(boolean){
        this.setState({test: !this.state.test})
    }

    render(){
        return (
            <div>
                <a test={this.state.test} />
                <b updateTest={this.updateTest}/>
            </div>
        )
    }
}

Upvotes: 4

Related Questions