Have been facing issue while iterating through a list and printing elements in React.
The React Code is:
import React from \'react\';
import ReactDOM fro
what you can do is extract your js code from the render method in a separate method like so:
renderList() {
return this.state.myData.map((item) => {
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
})
}
then in your render method:
render() {
if(this.state.myData.length){
return (
<div>{this.renderList()}</div>
);
}
else
{
return (
<div>Loading...</div>
);
}
}
You can wrap it with root element like div
,
React ver 15 render functions supports only returning one element.
render() {
<div>{this.state.myData.map((item) =>
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
)}</div>
}
}
I think you are missing the return in renderList -> .map
This should work.
renderList() {
return this.state.myData.map((item) => {
return (
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
);
});
}
render() {
if(this.state.myData.length){
return (
<div>{this.renderList()}</div>
);
}
else {
return (
<div>Loading...</div>
);
}
}
Change like this, While you using map
should use key
attribute for index
makeUI() {
if(!this.state.myData.length)
return
return this.state.myData.map((item, index) => {
return (
<div key={index}>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
)
})
}
render() {
return (<div>
{ this.makeUI() }
</div>
)
}