2

I'm trying to loop through a simple array inside a functional component so it returns list of names inside the array. The error I get is Person(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

const Person = () => {

  var persons = ["John", "Ron"];

  persons.map(p => {
    return  (
      <div> 
         <ul> 
            <li> I am {p} </li>
         </ul>
      </div>
    ) 
  })
}
2
  • you're not returning anything from the component, but only inside the map iteration Commented Aug 6, 2018 at 1:42
  • 1
    Also note that the block inside your map can be simplified to persons.map(p => (( <div ... </div> )); since it's technically a single line return statement Commented Aug 6, 2018 at 1:47

2 Answers 2

1
  • Repeat only the <li> inside map because it's List item.
  • Use array index as key as person name can be the same in the real scenario.

const Person = () => {
  var persons = ["John", "Ron"];

  return (
  <div>
      <ul>
        {
        	persons.map((p,i) => {
          	return (<li key={i}> I am {p} </li>)
        	})
        }
      </ul>
    </div>
    )
};

ReactDOM.render(<Person />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

You have to return the resulting array of map or undefined will be returned from the Person component, which React doesn't allow.

const Person = () => {
  var persons = ["John", "Ron"];

  return persons.map(p => (
    <div key={p}>
      <ul>
        <li> I am {p} </li>
      </ul>
    </div>
   ));
};

ReactDOM.render(<Person />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>

3 Comments

got it! map returns and then the component also returns
@Deke Practically the above solution is not completely correct as per me. As to list the People whole structure should not be repeated but only li should be repeated. As per above code whole structure of the div will be repeated for each person, which according to me is not correct.
@RonitMukherjee I think Deke knows that and can change that as he see fit. The question was more specifically why the error Person(...): Nothing was returned from render... occurred.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.