L
L
Li_Von2018-02-25 02:18:03
JavaScript
Li_Von, 2018-02-25 02:18:03

How to wire React components?

Hello.
The site has two components, let's say a button and text, when you click on the button, the data array for the text should change. But the problem is that these components cannot be crammed into one and thus use setState. How to decide?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-25
@Li_Von

Such tasks are easily solved through the parent:

class Parent extends Component {
  state = {
    text: 'some text',
  };

  handleClick = () => {
    this.setState({ text: 'some other text'});
  };

  render() {
    const { text } = this.state;

    return (
      <Wrapper>
        <Button onClick={this.handleClick} />
        <Text>{text}</Text>
      </Wrapper>
    );
  }
}

In a component structure, as in any other tree structure, it is physically impossible to arrange two components so that they are not in the same common parent. It is a fact.
If you are not using redux and the task is private, then passing a callback through a parent, and even through multiple components, can be a simple and effective solution.
Another thing is that in a more or less complex react application, it is good to use redux or analogues.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question