Reputation: 8550
Parent component initialized like so:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
children: [
{name: "Julien Lennon"},
{name: "Sean Lennon"}
]
}
}
render() {
return <div class="parent">Parent, called {this.props.name}
{this.state.children.map((child, index) => {
return (
<Child name="{child.name}" />
);
})}
</div>;
}
}
Now, in the child I just want to access the name prop:
class Child extends React.Component {
render() {
return <div class="child">Child named {this.props.name}</div>;
}
}
But its outputing the name as a literal: Child named {child.name}
fiddle: https://jsfiddle.net/89k1zcdp/6/
Upvotes: 0
Views: 56
Reputation: 68
You just need to remove the quotes around {child.name} in your Parent component's render function. Like this:
<Child name={child.name} />
Explanation:
In React, the HTML-like code is actually React's own templating language called JSX. In JSX, you can indicate that a section of code is meant to be interpreted as JavaScript by wrapping it in brackets: {}. But since "{child.name}"
is wrapped in those double quotes it turns the brackets and everything they contain into a string. Removing the quotes like so {child.name}
will reference the name property of the child object like you would expect JS to do.
Upvotes: 2