I have an arr.map rendered in html, how can I do it to select one of them
my arr is like [{progress: "A" , _id: "123456"}, {progress: "A" , _id: "222363"} , ....... ]
Example: Press the first btn to select arr[0]. Press the third btn to select arr[2].
Below is the html document
arr.map((arr) => (
<div className={arr._id} id="bookingdata" >
<div className="booking-detail">
<p className="booking-id" id="booking-id">
{arr._id}
</p>
<p className="booking-progress">
{arr.progress}
</p>
<button onClick={handledetail} className="btn">
btn
</button>
</div>
</div>));
CodePudding user response:
In your array of objects add one more field as isSelected and mark it as false intially
const [data,setData]=useState(arr)
data.map((arr) => (
<div className={arr._id} id="bookingdata" >
<div className="booking-detail">
<p className="booking-id" id="booking-id">
{arr._id}
</p>
<p className="booking-progress">
{arr.progress}
</p>
<button onClick={()=>{arr.isSelected=true}} >
btn
</button>
</div>
</div>));
CodePudding user response:
Many ways to do it.
If u will have a lot of items, and u want to solve it with a single handler, u can do something like this:
(in your css u will need a "selected" class)
const [selectedId, setSelectedId] = useState();
function handledetail(e) {
setSelectedId(e.currentTarget.dataset.id); // if "_id" is number Number(e.currentTarget.dataset.id)
...
}
data.map((item) => (
<div className={`${item._id} ${selectedId === item._id ? "selected" : ""}`} id="bookingdata" >
<div className="booking-detail">
...
<button onClick={handledetail} data-id={item._id} className="btn">
btn
</button>
</div>
</div>
));