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
Add a ment  | 

2 Answers 2

Reset to default 5

You 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