7

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!

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to offset this? Like if you want the rest of the data wrapped in a different div for example.
@budji: For the rest of the data, you could just slice the array: this.state.data.slice(1).map(x => ...)
Not working still it's this.state.data[0] is undefined
If there is a chance that this.state.data[0] will be undefined, you must handle that in your code.
1

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>

1 Comment

I am new in reactjs. how can i use lodash in react.
1

This solution works correctly.

{data.map((data, i) =>
    <span className="fooBar">
        <a href={data.foo}>{data.bar}</a>
    </span>
)[0]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.