Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
React - Set default attribute while using map()

I want to render tabs that I stored in an array and set the first tab in the array as default.

Not using an array, it would look kind of like this:

<Tab
   name={"first tab"}
   default
/>
<Tab
   name={"second tab"}
/>

But now since I'm using an array and mapping through it, I'm wondering how i can set the default attribute for the first tab.

This is how the array looks like:

  const tabs = [
{
  name: "first tab",
  
},
{
  name: "second tab",
}]

This is my map function:

    {tabs.map(tab => (
      <Tab
        name={tab.name} />
    )}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

map passes your callback the index of the entry as the second argument, so:

{tabs.map((tab, index) => (
    <Tab
        key={tab.name}
        name={tab.name}
        default={index === 0}
    />
)}

Note I've also added a key, since you need that whenever you give an array to React.

about 4 years ago · Juan Pablo Isaza Report

0

The second argument to the callback you pass to map is the index.

The first item will have an index of 0 (which is false).

So capture that and then you can just: default={!index}

about 4 years ago · Juan Pablo Isaza Report

0

Use the array index, the default tab would be index 0, or all truthy indices would not be default.

{tabs.map((tab, i) => (
  <Tab
    key={tab.name}
    default={!i}
    name={tab.name} />
)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!