Reputation: 3548
I have this React-component called PersonCard:
class PersonCard extends Component {
constructor(props) {
super(props);
console.log(JSON.stringify(props));
this.state = props;
}
render() {
return (
<div>
<MuiThemeProvider muiTheme={Mui} >
<Card>
<CardHeader
title={this.props.firstName}
/>
</Card>
</MuiThemeProvider>
</div>
);
}
}
export default PersonCard;
The view has multiple PersonCards and they're mapped from an array in its parent component SearchResults as follows:
class SearchResults extends Component {
constructor() {
super()
this.state = {
data: [],
}
}
componentDidMount() {
return fetch('http://localhost:3005/persons')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data:responseJson
})
})
}
render() {
return (
<div>
{
this.state.data.map( (person)=>
<PersonCard key={person.id} personProp = {person} />
)
}
</div>
)
}
}
export default SearchResults;
The logger in the constructor shows the person objects and their properties correctly, so it's there as it should be.
BUT the props value (this.props.firstName) doesn't show in the render-method, since they get rendered as "undefined" on the view. Why?
Upvotes: 0
Views: 878
Reputation: 359
In your code you are pass "key" and "personProp" props to "PersonCard" components. So inside the render function of "PersonCard" component you can access these props by "this.pops.key" and "this.props.personProp".
So if your personProp contain's the firstName then you will be able to access it by "this.prps.personProp.firstName". So you should try below code
class PersonCard extends Component {
constructor(props) {
super(props);
console.log(JSON.stringify(props));
this.state = props;
}
render() {
return (
<div>
<MuiThemeProvider muiTheme={Mui} >
<Card>
<CardHeader
title={this.props.personProp.firstName}
/>
</Card>
</MuiThemeProvider>
</div>
);
}
}
export default PersonCard;
Upvotes: 1
Reputation: 4008
You don't define a prop called firstName
here:
<PersonCard key={person.id} personProp = {person} />
Maybe you meant to access it through this.props.personProp.firstname
?
Upvotes: 4