简体   繁体   中英

React.js A valid React element (or null) must be returned

I am new in React and I am not sure why it cause error, it threw

Uncaught Error: SearchBar.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object

Note that, the props.courses is a hash inside array object like

[
  {"id": "1", "course_name": "ABC"},
  {"id": "2", "course_name": "EFG"}
]

Here is the code

render () {
  if (!this.props.courses)
    return (
      <div className="">
        Loading...
      </div>
    );

  return (
    this.props.courses.map((course) => {
      return (
        <div> {course["course_name"]} </div>
      )
    })
  );
}

Render should always return single element. Also you need to wrap you .map function with {} .

render () {
  if (!this.props.courses)
    return (
      <div className="">
        Loading...
      </div>
    );

  return (
    <div>
      {this.props.courses.map((course) => {
        return (
          <div> {course["course_name"]} </div>
        )
      })}
    </div>
  );
}

If there are courses, you are returning an array of React elements. This does not work, an array of elements is not a valid React element. You can fix this by simply wrapping that array in a div element, then it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM