How to communicate between independent components in React.JS?

I am new to React.JS and trying to understand the following. Imagine that I have two components: two HTML text inputs; I want to achieve the following: when the user changes the text in the first text field - the changes appear simultaneously in the second text field; and vice versa - when the user changes the text in the second text file - this change also appears in the first. What is the right way to do this in a responsive way? What should be written in handlers onChange?

+4
source share
2 answers

Personally, I like the event-based approach. It's easy to implement the Pub / Sub template using a small library (like PubSubJS ) or folding your own using your own events.

I wrote a little more about the latter here: http://maketea.co.uk/2014/03/05/building-robust-web-apps-with-react-part-1.html#component-communication

+3
source

As long as both of your form inputs are: (1) managed inputs and (2) have a property valuethat points to the same data, any change to this data will update both inputs.

/** @jsx React.DOM */

var SyncEdit = React.createClass({
  getInitialState: function() {
    return { text: "" };
  },

  render: function() {
    return (
      <div>
        <input type="text" value={this.state.text} onChange={this.handleChange} />
        <input type="text" value={this.state.text} onChange={this.handleChange} />
      </div>
    );
  },

  handleChange: function(evt) {
    this.setState({text: evt.target.value});
  }
});

React.renderComponent(<SyncEdit />, document.body);

Here's the JSFiddle for a demo : http://jsfiddle.net/BinaryMuse/2K5qX/

+2
source

Source: https://habr.com/ru/post/1541913/


All Articles