Home > Enterprise >  How to add class on first record in array using Reactjs
How to add class on first record in array using Reactjs

Time:11-18

I am working in Reactjs and using Nextjs,I am trying to add class(active) on "first id"/array first record (fetching from db) but right now working with statically "where id=1" instead of First record,How can i do this ? in other words i want to add active on "first record(in array)" not "where id=1", I tried with following code

{this.state.trending.map((post, index) => {
      return (
                <>
                <div className={`carousel-item ${post.id == 1 ? 'active' : ''}`}>
            )
       })}

CodePudding user response:

Use index instead of post.id. Compare it to 0 instead of 1 and you should be just fine.

this.state.trending.map((post, index) => (
  <div className={`carousel-item ${index === 0 ? 'active' : ''}`}>
)

CodePudding user response:

Try this

this.state.trending.map((post, index) => (
  <div className={"carousel-item" ((index == 0)? 'active':'')}>
)
  • Related