admin管理员组文章数量:1378759
Here I'm trying to return each item in the array as an h1 so the print to screen should look like:
1
2
3
4
5
However I get this error:
Warning: Charts(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
How can I achieve this?
import React from 'react';
function NoCharts(props) {
return <h1>No charts</h1>;
}
function Charts(props) {
const myCharts = props.myCharts;
if (myCharts.length > 0) {
myCharts.forEach(function(chart) {
return <h1>{chart}</h1>;
});
}
return <NoCharts />;
}
export default class App extends React.Component {
render() {
let arr = [1,2,3,4,5];
return (
<div>
<Charts myCharts={arr} />
</div>
)
}
}
Here I'm trying to return each item in the array as an h1 so the print to screen should look like:
1
2
3
4
5
However I get this error:
Warning: Charts(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
How can I achieve this?
import React from 'react';
function NoCharts(props) {
return <h1>No charts</h1>;
}
function Charts(props) {
const myCharts = props.myCharts;
if (myCharts.length > 0) {
myCharts.forEach(function(chart) {
return <h1>{chart}</h1>;
});
}
return <NoCharts />;
}
export default class App extends React.Component {
render() {
let arr = [1,2,3,4,5];
return (
<div>
<Charts myCharts={arr} />
</div>
)
}
}
Share
Improve this question
asked Jul 12, 2017 at 0:03
fromspacefromspace
3753 silver badges19 bronze badges
2 Answers
Reset to default 5You must "return" a valid React element, as the error says -
Charts(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
if (myCharts.length > 0) {
const charts = myCharts.map(function(chart) {
return <h1>{chart}</h1>;
});
return <div>{charts}</div>
}
else {
return <NoCharts />;
}
}
Here's the working app on codepen.
You need to return myCharts. Currently you're only returning something when the array is empty.
return myCharts.forEach(function(chart) {
return <h1>{chart}</h1>;
});
本文标签: javascriptReact Conditional Rendering Of Components And ArraysStack Overflow
版权声明:本文标题:javascript - React: Conditional Rendering Of Components And Arrays - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744470321a2607760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论