Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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 ?

like image 676
Whisher Avatar asked Mar 14 '15 16:03

Whisher


People also ask

How do you get a prop from a child to a parent?

To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive.

How do you pass data from a child to parent in react using props?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .


1 Answers

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.

like image 121
Max Heiber Avatar answered Sep 29 '22 23:09

Max Heiber