1

After playing around with react I noticed a strange behavior while outputting array:

function bar1() {
  let arr = [0, 1];
  return arr.map((el) => foo(el))
}

function bar2() {
  let arr = [0, 1];
  arr = arr.map((el) => foo(el))
  return (
    {arr}
  )
}

function foo(key) {
  return (
    <div key={key}>Foo</div>
    )
}

I would expect bar1() and bar2() to output identical results, however bar2() throws error:

Objects are not valid as a React child (found: object with keys {arr}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

I need to insert additional element in bar2() after map operation, that's why i can't use the simplified version.

Is it a bug related to JSX or it behaves as expected?

3
  • That error is self explanatory. React can't render Objects in render output. Commented Jan 14, 2017 at 0:18
  • Remove the brackets. arr != {arr} Commented Jan 14, 2017 at 0:21
  • It doesn't give me error in JSfiddle... jsfiddle.net/psiho/gL05ddfg Commented Jan 14, 2017 at 0:25

1 Answer 1

2

To answer your question - it's not a bug, it's an expected behavior.

When you return {arr}, you essentially return a {arr: arr} object because Babel understands it as an ES6 object shorthand (see property definition). In order to have the same output from both of your functions, you should remove the curly braces from your bar2() function's return statement.

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

Comments

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.