Reputation: 3888
I am new to react.js and I just started reading a book that showcases nested components and shows how to pass an attribute to the child element. This is the example.
var GreetingComponent = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
var GenericComponent = React.createClass({
render: function() {
return <GreetingComponent name={this.props.name} />;
}
});
React.render(<GenericComponent name="World" />,
document.getElementById('container'));
As the book says "Starting from a top-level attribute on the GenericComponent, you can pass this attribute by using this.props to the child element GreetingComponent." and this is why "Hello World" is rendered.
But, what if I want, for the sake of argument, the same structure, but I want every components to have a different prop value, like
var GreetingComponent = React.createClass({
render: function() {
return <div>Hello {this.props.anotherName}</div>;
}
});
var GenericComponent = React.createClass({
render: function() {
return <GreetingComponent name={this.props.name} />;
}
});
React.render(<GenericComponent name="World" anotherName="Earth"/>
document.getElementById('container'));
Check it here.
This is not working and nothing is rendered.
How can I have two nested components with different prop values? Please explain and help me understand.
Thank you.
Upvotes: 1
Views: 288
Reputation: 4704
For <GreetingComponent name={...} />
to work, GreetingComponent
must have a name
property.
Since GenericComponent
renders GreetingComponent
, you must pass the name to GenericComponent
as a property, called greetingName
for instance, so that it will pass it to GreetingComponent
as name
.
Now, you want GenericComponent
to have a name of its own, so you must give it a second prop.
See a solution here: https://jsfiddle.net/5kk90t0k/.
Upvotes: 1