Why does object.property not work, when object.property.toString() does when binding?

Viewed 41

I'm a total React beginner.

This works, where I reference opportunity.title.toString() (which seems redundant):

function BindOpportunities(opportunities) {
    const listItems = opportunities.map((opportunity) =>
       <li key="{opportunity.opportunityId}">{opportunity.title.toString()}</li>
    );

    ReactDOM.render(
        <ul>{listItems}</ul>,
        document.getElementById('opportunity-list-view')
    );
}

And produces the output:

<li>Help Us Spread The Work About www.ImmuneAndReadyToHelp.com!</li>

...where the object looks like:

{"opportunityId":"00000000-0000-0000-0000-000000000000","title":"Help Us Spread The Work About ImmuneAndReadyToHelp.com!"}

However, this does NOT work where I use "property" without .toString(). Can anyone help me understand why?

function BindOpportunities(opportunities) {
    const listItems = opportunities.map((opportunity) =>
       <li key="{opportunity.opportunityId}">{opportunity.title}</li>
    );

    ReactDOM.render(
        <ul>{listItems}</ul>,
        document.getElementById('opportunity-list-view')
    );
}

NOTE: in response to a comment, I get the warning:

react-dom.development.js:82 Warning: Encountered two children with the same key, {opportunity.opportunityId}. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

1 Answers

First thing, don't use ReactDOM.render() inside a child node, you just need this for root node like <App /> and then children nodes/components just need to return the jsx in function components and return from render method in case of class base components

function BindOpportunities({ opportunities }) {
    return (
       <ul id="opportunity-list-view">
       { opportunities.map((opportunity) =>
       <li key={opportunity.opportunityId}>{opportunity.title}</li>
    )}
    </ul>
    );
}

const opportunities = [
  {
     "opportunityId":"00000000-0000-0000-0000-000000000000",
     "title":"Help Us Spread The Work About ImmuneAndReadyToHelp.com!"
  }
];

function App () {
   return (
     <BindOpportunities opportunities={opportunities} />
   );
}

ReactDOM.render(<App />, document.getElementById('root'));

Related