Easiest React form dropdown and other tricks

I use the map() method so much it deserves it's own blog post. I use it every time I need to render components for each item in a dataset.

I'm making a form. I need a dropdown. Here's how I do that.

Say we have an array of options:

types = ["Toyota","Hyundai","Honda"];

In the render function, use map() to generate an option for each array element:

<select id="type" onChange={this.handleTypeChange}>
    {this.types.map(x => <option key={x}>{x}</option>)}
</select>

Boom, solved.

That option element might as well be a react component, and each mapped item can be fed to the component as a prop.

<nav id="main-navigation">
    {this.props.links.map(item => <NavItem key={item.id} item={item}/>)}
</nav>

Sometimes you can't be sure that the array you're trying to map actually contains any data. The quickest way to be safe is to use a shorthand logical operator.

{this.props.links && this.props.links.map(item => <NavItem key={item.id} item={item}/>)}

These patterns really shape the way I write all of my components. It's basic stuff, but it's important to get the basics right.