0

How could I access to the element in state array for example

this.state = {
    items: [1,5,22,6],
}

here I'm trying to set up a class if the id exists in items state

{this.props.data.map((row)=> (
 <ul>
  <li key={row.id} className={row.id === this.state.items ? 'complete' : 'pending'}" >{row.name}</li>
</ul>

))}

1 Answer 1

3

You can use the .includes() function for arrays:

{this.props.data.map((row)=> (
   <ul>
     <li key={row.id} className={this.state.items.includes(row.id) ? 'complete' : 'pending' }>{row.name}</li>
   </ul>
))}

Alternatively use .indexOf():

{this.props.data.map((row)=> (
   <ul>
     <li key={row.id} className={this.state.items.indexOf(row.id) !== -1 ? 'complete' : 'pending' }>{row.name}</li>
   </ul>
))}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that .includes() astonishingly isn't supported in IE.

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.