How to pass state with parent to child component
There is but it's not intended to work like that in React. 2-way data binding isn't the way to go in React, excerpt from the docs.
In React, data flows one way: from owner to child.
So what you want to do if you want to manipulate parent state in your child component is passing a listener.
//parent component's render functionreturn ( <Child listenerFromParent={this.doSomething} />)//child component's render functionreturn ( <div onClick={this.props.listenerFromParent}></div>)
You can use the limelights solution, ie passing a function from the parent to the child.
Or you can also use projects like React-Cursor which permits to easily manipulate state passed from a parent component in a child.
I have made my home made framework (Atom-React, some details here) that also use cursors (inspired by Om), and you can somehow achieve easily 2-way data binding with cursors permitting to manipulate the state managed by a parent component.
Here's an exemple usage:
<input type="text" valueLink={this.linkCursor(this.props.inputTextCursor)}/>
The inputTextCursor
is a cursor passed from a parent to a child component, and thus the child can easily change the data of the parent seemlessly.
I don't know if other cursor-based React wrappers use this kind of trick but the linkCursor
function is implemented very easily with a simple mixin:
var ReactLink = require("react/lib/ReactLink");var WithCursorLinkingMixin = { linkCursor: function(cursor) { return new ReactLink( cursor.getOrElse(""), function setCursorNewValue(value) { cursor.set(value); } ); }};exports.WithCursorLinkingMixin = WithCursorLinkingMixin;
So you can easily port this behavior to React-Cursor