I'm newbie in React.JS and trying to understand the following thing. Imagine that I have two components: two HTML text inputs; what I want to achieve is the following: when a user changes the text in first text field - changes appears at the same time in a second text field; and vice versa - when a user changes the text in second text filed - the change also appears in the first one. What is the right way to do it in a react way? What should be written in the onChange
handlers?
I saw that the question is already answered, but if you'd like to learn more details, there are a total of 3 cases of communication between components: Case 1: Parent to Child communication. Case 2: Child to Parent communication. Case 3: Not-related components (any component to any component) communication.
You can also pass events like onClick or OnChange Just call an alert method in the childToParent function and pass that function as a prop to the child component. And in the child component, accept the childToParent function as a prop. Then assign it to an onClick event on a button. That's it!
To do that, I casted the children (received in props by Parent) in to local state. Appended the prop to each child to have a callback function to communicate with the parent. The Parent component now returns the state variable that has the modified / appended props, instead of returns prop. children as it received!
The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.
Personally I like an event-driven approach. It's easy to implement a Pub/Sub pattern either using a little library (such as PubSubJS) or rolling your own with native 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
As long as both your form inputs are (1) controlled inputs and (2) have a value
property pointing to the same data, any change to that 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 a JSFiddle to demonstrate: http://jsfiddle.net/BinaryMuse/2K5qX/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With