R.K R.K - 2 months ago 5
React JSX Question

how to properly iterate through array of post objects retrieved through Wp Rest Api in react js

hello :) i am working on wp rest api and react js and i successfully retrieved data from wp rest api and displayed it, but its not the proper way to display data in react. console is showing the error message of ' Each child in an array or iterator should have a unique "key" prop ' . I read the document in react regarding the issue but didn't understood . Here is what i have written so far. Any help would be great thank you

class Home extends React.Component{
componentDidMount(){
const API_URL = 'http://localhost/wordpress/wp-json/wp/v2/posts/';
this.serverRequest = $.get(API_URL, function (result) {
this.setState({
result:result,
loaded:true
});
}.bind(this));
}
constructor(props) {
super(props);
this.state ={result:null,loaded:false};
autoBind(this);
}
render(){
if (this.state.loaded) {
return(
<div>
{this.state.result && <Portfolio data = {this.state.result}/>}
</div>
)
}
return(
<div>loading...
</div>
)

}
}
export default Home;


and the Portfolio component to which prop data is passed renders the data like this which is not the proper way

class Portfolio extends React.Component{
constructor(props) {
super(props);
autoBind(this);
}
render(){
var contents=[];
for (var i = 0; i < this.props.data.length; i++) {
if (this.props.data[i].categories[0] == 5) {
var productImage ={
backgroundImage:'url('+ this.props.data[i].featured_image + ')',
backgroundSize: '100% 100%'
}
contents.push(
<div id="portfolio-product-item" style ={productImage} >
<div id ="portfolio-product-item-details" >
<h3>{this.props.data[i].slug}</h3>
<div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
</div>
</div>
);
}
}
return(
<section className="portfolio">
{contents}
</section>
)
}
}
export default Portfolio;

Answer

I haven't went over all of your code, just relating to the "key" error you got. The issue is here -

contents.push(
        <div  id="portfolio-product-item" style ={productImage} >
          <div id ="portfolio-product-item-details" >
            <h3>{this.props.data[i].slug}</h3>
            <div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
          </div>
        </div>
  );

The father div with the id of portfolio-product-item should also have an attribute key so the proper way to write it is -

contents.push(
        <div  key={i} id="portfolio-product-item" style ={productImage} >
          <div id ="portfolio-product-item-details" >
            <h3>{this.props.data[i].slug}</h3>
            <div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
          </div>
        </div>
  );

Have a look at - https://facebook.github.io/react/docs/multiple-components.html#dynamic-children for further info.

Comments