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 ?
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With