pmiranda
pmiranda

Reputation: 8420

React, Nothing was returned from render

I have this Home component:

import Items from './Items';
class Home extends Component{
  render(){
    const { items } = this.props;

    return(
      <div className="container">
          <Items items={items}/>
      </div>
    )
  }
}

And Items is this one:

import React from 'react';
const Items = (props) => {
    const { items } = props;
    items.map(item=>{
      return(
        <div>
            <p>{item.value}</p>
        </div>
      )
    });
};

export default Items;

I'm getting this error:

× Error: Items(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Why? How can I return something if I need to map those items array.

Upvotes: 1

Views: 241

Answers (1)

Yuan-Hao Chiang
Yuan-Hao Chiang

Reputation: 2603

When you do return inside a map() (or any function that uses a callback), you need to add the extra return for the React component:

const Items = (props) => {

    const { items } = props;

    return items.map(item=>{
    ^^^^^^
      return(
        <div>
            <p>{item.value}</p>
        </div>
      )
    });
};

You can simplify the inner callback inside the map() by using regular parenthesis:

return items.map(item=> (
  <div>
     <p>{item.value}</p>
  </div>
));

This is called implicit return which works when there is no block scope { ... } inside of arrow functions. So:

// These are all equivalent: return value is: [2,4]

[1,2].map(n => n * 2);
[1,2].map(n => (n * 2));
[1,2].map(n => { return (n * 2) });

// This, howover, will return [ undefined, undefined ] because
// there is no return inside the block-scope of the arrow function:

[1,2].map(n => { n * 2 });

Same with any kind of arrow function (such as the way you defined the <Items> component:

// This will work:

const Items = () => (
  items.map(item => ...)
);

// This will return undefined, and React won't like it:

const Items = () => {
  items.map(item => ...)
}

Hope the explanation makes sense and add any comment if something is unclear!

Finally, if you ever wished to not return anything from a render() or functional component, returning null will suffice:

  if (!props.items) {
    return null; // <-- this works
  }

  ...
}

Upvotes: 1

Related Questions