I'm making my first step in ReactJS and trying to understand communication between parent and children.
I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:
var LoginField = React.createClass({
render: function() {
return (
<MyField icon="user_icon" placeholder="Nickname" />
);
},
check: function () {
console.log ("aakmslkanslkc");
}
})
var MyField = React.createClass({
render: function() {
...
},
handleChange: function(event) {
//call parent!
}
})
Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.
Best Answer
To do this you pass a callback as a property down to the child from the parent.
For example:
In the above example,
Parent
callsChild
with a property ofvalue
andonChange
. TheChild
in return binds anonChange
handler to a standard<input />
element and passes the value up to theParent
's callback if it's defined.As a result the
Parent
'schangeHandler
method is called with the first argument being the string value from the<input />
field in theChild
. The result is that theParent
's state can be updated with that value, causing the parent's<span />
element to update with the new value as you type it in theChild
's input field.