Coty Embry
Coty Embry

Reputation: 978

use .map during component composition in reactjs

I can render the following completely fine:

    <Select
      defaultValue=''
    >
        <Option value='' />
        <Option value='one' />
        <Option value='two' />
    </Select>

but what I want to do is compose a collection of n number of custom Option components as children that will be used during the component's render method:

    <Select
      defaultValue=''
    >
        {
          this.props.optionValues.map((value, i) =>
            <Option key={i} value={value} />
          )
        }
    </Select>

But I'm struggling and cant find much documentation about this context of rendering components specifically

Does this work at all or not make sense due to how jsx is?

Upvotes: 1

Views: 269

Answers (1)

Tholle
Tholle

Reputation: 112887

Rendering arrays as children is perfectly valid if each element has a unique key prop like you have outlined in your question. Granted that your this.props.optionValues array looks like ['', 'one', 'two'] it will work fine.

Example

function App(props) {
  return (
    <div>
      <select>
        <option value="">Pick number</option>
        <option value="one">One</option>
        <option value="two">Two</option>
      </select>
      <select>
        <option value="">Pick number</option>
        {props.optionValues.map((value, i) => (
          <option key={i} value={value}>
            {value}
          </option>
        ))}
      </select>
    </div>
  );
}

ReactDOM.render(
  <App optionValues={["one", "two"]} />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

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

Upvotes: 1

Related Questions