Ad

React Passing Data To Components With JSX Vs Native Javascript

This should be a simple one. I'm using JSX and ES6 with Babel to transpile my JSX and ES6, and those aspects are definitely working. However, when I'm running into a stumbling block with trying to pass data to the ContactItem Component via a JSX styled call. See the simple example below...

const contacts = [
    {key: 1, name: "Bob"},
    {key: 2, name:"Dude"}
  ]

class ContactItem extends React.Component {
   ...
}

// the following Javascript call works to loop through each contact and pass the data to ContactItem 
const contactListItems = contacts
  .map(contact => { return React.createElement(ContactItem, contact); });

// While using JSX, the contact data is not flowing through to ContactItem.
const contactListItemsJSX = contacts
  .map(contact => { return <ContactItem contact /> });

Why is the data not being passed when using <ContactItem contact />?

Ad

Answer

The equivalent of

React.createElement(ContactItem, contact);

in JSX is

<ContactItem {...contact} />;

See JSX Spread Attributes for more information.

Ad
source: stackoverflow.com
Ad