Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSX map only the first object in array

Tags:

reactjs

jsx

I'm curious on how to only render the first object in an array using .map in JSX.

{this.state.data.map(data =>
    <span className="fooBar">
        <a href={data.foo}>{data.bar}</a>
    </span>
)}

Thank you!

like image 855
Samantha Ingram Avatar asked May 26 '16 13:05

Samantha Ingram


2 Answers

The easiest solution would be to just not use .map at all!

<span className="fooBar">
    <a href={this.state.data[0].foo}>{this.state.data[0].bar}</a>
</span>

.map will always go over every object in an array - there's no way to break out of it early.

like image 175
Joe Clay Avatar answered Oct 23 '22 16:10

Joe Clay


Map is designed to call every element in an array applying a transformation.

If you just want to render the first then you'd be better to either explicitly call the first element this.state.data[0] or use a library that supports a method like head.

Lodash Example

const link = _.head(this.state.data);
<span className="fooBar">
  <a href={link.href}>{link.title}</a>
</span>
like image 39
Tim Reynolds Avatar answered Oct 23 '22 14:10

Tim Reynolds