Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to save all Button values in array using ReactJs

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.

enter image description here

like image 583
Adnan Arif Avatar asked Jun 23 '26 17:06

Adnan Arif


1 Answers

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
])

How it can be used:

const onClick = (ev) => {
  const value = ev.target.value
  setter(prevState => [
    ...prevState,
    value
  ])
}

<button onClick={onClick} value="1">Click Me</button>
like image 132
koralarts Avatar answered Jun 25 '26 10:06

koralarts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!