Reputation: 2159
I have an Article component and a state with all my articles. I map state to props with the right article I want to display.
console.log(props.article)
works but console.log(props.article.title)
or any other attribute does not (I get Cannot read property 'id' of undefined
). why ?
My Article.js
component:
import React from 'react';
import { connect } from 'react-redux';
const Article = props => (
<div className="aboutpage-wrapper">
<div className="container">
{ console.log(props.article)}
{/* <h2>{props.article.title}</h2>
<h3>{props.articlesubtitle}</h3>
<p>{props.article.body}</p>*/}
</div>
</div>
);
const mapStateToProps = (state,props) => ({ article: state.articles.find(function (article) { return article.id === props.match.params.id; })});
export default connect(mapStateToProps)(Article);
Upvotes: 2
Views: 1255
Reputation: 3356
The answer drills down the unavailability of props and hence the respective collection inside them.
You should first check for the availability of your prop. You can use the ES6 destructuring operator as:
const { article } = this.props;
which is same as the
const article = this.props.article ? this.props.article : '';
Additionally, while rendering out the content inside you can use the same logic for the availability of content inside the article
as:
<h2>{props.article.title ? props.article.title : '' } </h2>
While rendering the content, you can also write like this:
<h2>{(props.article || {}).title || ''} </h2>
I hope this will help.
Cheers!
Upvotes: 1