Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass state with parent to child component

Is there any way passing state from parent component to child component like:

var ParentComponent = React.createClass({
  getInitialState: function() {
    return {
      minPrice: 0
    }
  },
  render: function() {
    return (
      <div onClick={this.doSomething.bind(this, 5)}></div>
    );
  }
});

var ChildComponent = React.createClass({
  getInitialState: function() {
    return {
      minPrice: // Get from parent state
    }
  },
  doSomething: function(v) {
    this.setState({minPrice: v});
  },
  render: function() {
    return (
      <div></div>
    );
  }
});

I want to change parent state value from child component. In react.js is it possible or not?

like image 623
Eniz Gülek Avatar asked Oct 23 '14 06:10

Eniz Gülek


2 Answers

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 function
return (
   <Child listenerFromParent={this.doSomething} />
)

//child component's render function
return (
  <div onClick={this.props.listenerFromParent}></div>
)
like image 51
Henrik Andersson Avatar answered Nov 20 '22 12:11

Henrik Andersson


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

like image 2
Sebastien Lorber Avatar answered Nov 20 '22 12:11

Sebastien Lorber