Answer the question
In order to leave comments, you need to log in
How to change state in all React component instances?
Just started learning React. There is a button component and there can be many such buttons on the page. How, when clicking on any of the buttons, change the state in all instances of this component? this.setState only works on the button that was clicked
Answer the question
In order to leave comments, you need to log in
To do this, each instance needs to pass a reference to one value
class Buttons extends Component {
state = {
foo: 'bar'
}
changeText = () => {
if (this.state.foo === 'bar') {
this.setState({ foo: 'foo' })
} else {
this.setState({ foo: 'bar' })
}
}
render() {
return (
<Button text={this.foo} />
<Button text={this.foo} />
<Button text={this.foo} />
<Button text={'Изменить текст'} onClick={this.changeText} />
)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question