I have 3 buttons with the same name and different values, I want when i click on any button, it's getting value and save in array. e.g [1,2].
here's my code
import React, { useState } from "react";
const UserDetails = ({ navigation }) => {
// Here i make a state
const [selecthostingOption, setselecthostingOption] = useState([]);
const hostingChange = e => {
e.preventDefault();
console.log(e.target.value);
setselecthostingOption(e.target.value);
};
return (
<>
<button onClick={hostingChange} name="selecthostingOption" value="1">
Value 1
</button>
<button onClick={hostingChange} name="selecthostingOption" value="2">
Value 2
</button>
</>
);
};
export default UserDetails;
I have attached the image.

When you call the set function like so setselecthostingOption(e.target.value), you're not pushing the value into the array but you're replacing the array with whatever value is assigned to e.target.value.
For you to be able to push into your state, you'll need to give it the new array with your value in it.
setselecthostingOption(prevState => [
...prevState,
newValue
])
const onClick = (ev) => {
const value = ev.target.value
setter(prevState => [
...prevState,
value
])
}
<button onClick={onClick} value="1">Click Me</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With