M
M
Maxim Zolotoy2019-01-16 20:44:44
React
Maxim Zolotoy, 2019-01-16 20:44:44

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

1 answer(s)
A
Askhat Bikmetov, 2019-01-16
@spacenear

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} />
    )
  }
}

The example is stupid, but the principle illustrates.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question