-1

I have this code

{categories.map((category, index) => {
  return(
    <option value={category._id} key={index}>{category.name}</option>
  )
})}

This code display all categories. And I have const product

How to make if product.category == category._id add attribute selected to select( in map function )

Dan
  • 179
  • 9

2 Answers2

1

You can use selected={product.category == category._id} but it's not recommended, you should use the value attribute in the select tag. Reference

Stutje
  • 416
  • 5
  • 11
0

Try this, this should resolve your issue. I have applied the condition as per your requirement inside the map function.

{categories.map((category, index) => {
  return(
    product.category == category._id ? <option value={category._id} key={index} selected>{category.name}</option>: <option value={category._id} key={index}>{category.name}</option> 
  )
})}
Antier Solutions
  • 1,094
  • 5
  • 9