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>
      )
    })
  );
}

Answers:

Answer

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>
  );
}
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.