Whisher
Whisher

Reputation: 32716

React what's the right way to get a parent props from its children

Be patient I'm new at React.

In this snippet (it doesn't work) I want,

in the CommentForm, to get the value of url props

from the CommentBox.

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm />
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: function() {
    return (
      <div className="commentList">
        Hello, world! I am a CommentList.
      </div>
    );
  }
});

var CommentForm = React.createClass({
  render: function() {
    return (
      <div className="commentForm">
        Hello,  my test url {this.props.url} !.
      </div>
    );
  }
});

React.render(
  <CommentBox url="api/comments" />,
    document.getElementById('content')
);

What's the right way ?

and why the props is not available directly from the parent to the children ?

Upvotes: 5

Views: 24223

Answers (1)

Max Heiber
Max Heiber

Reputation: 15502

You need to explicitly pass the props from parent to child. Changing the render function of CommentBox will fix the problem:

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        //The next line is where you can pass the URL to the CommentForm
        <CommentForm url={this.props.url}/>
      </div>
    );
  }
});

Working jsfiddle adapted from your example: http://jsfiddle.net/kb3gN/10352/

The docs say "For parent-child communication, simply pass props." See http://facebook.github.io/react/tips/communicate-between-components.html

As an alternative to explicitly passing props, React's undocumented context feature is closer to what you're looking for: https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html and is on the roadmap for 1.0 https://facebook.github.io/react/blog/2014/03/28/the-road-to-1.0.html#context.

That said, passing props is the normal pattern.

Upvotes: 11

Related Questions