Reputation: 3
Currently learning react 'props'. When rendering props inside a component i get an error on compile when passing 'name' and 'age':
"Cannot read property 'name' of undefined."
Here is my code:
Dashboard
import React, { Component } from 'react';
import SummaryWidget from '../../Components/SummaryWidgets/SummaryWidget';
class Dashboard extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="6" lg="6">
<SummaryWidget name='David' age='20'/>
</Col>
<Col xs="12" sm="6" lg="6">
</Col>
</Row>
</div>
)
}
}
export default Dashboard;
SummaryWidget
import React, { Component } from 'react';
class SummaryWidget extends Component {
constructor(props) {
super(props);
}
render (props) {
return (
<div className="SummaryWidget">
<span>{props.name}{props.age}</span>
</div>
)
}
}
export default SummaryWidget;
Upvotes: 0
Views: 116
Reputation: 3407
Change your SummayWidget Component from
class SummaryWidget extends Component {
constructor(props) {
super(props);
}
render (props) {
return (
<div className="SummaryWidget">
<span>{props.name}{props.age}</span>
</div>
)
}
}
to
class SummaryWidget extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="SummaryWidget">
<span>{this.props.name}{this.props.age}</span>
</div>
)
}
}
You do not need to add render (props)
like this in a class component.
If you need a class component do like above, or if you need a functional component do like @kevin suggested.
Upvotes: 0
Reputation: 1319
Please change render method to
render () {
return (
<div className="SummaryWidget">
<span>{this.props.name}{this.props.age}</span>
</div>
)
}
BTW: If you do not want to do anything in the constructor, you do not have to implement it. Also, if you do not need states and any life cycle method, you should make your component as a stateless component. Like:
import React from 'react';
const SummaryWidget = ({ name, age }) => (
<div className="SummaryWidget">
<span>{name}{age}</span>
</div>
);
export default SummaryWidget;
Upvotes: 2