Adnan Arif
Adnan Arif

Reputation: 107

Add and delete value from an array in react dynamically

I have multiple buttons in react, once I click on the button, its value is saved in an array. I want, when I click on any button that its value is saved only once, after click on that button again the value should be removed from an array.

e.g.

When I press "click 1" button the array value should be ["1"] and change the button color, after second click it should be removed.

import React, {useState} from 'react'; 
const UserDetails = () => {
const [selecthostingOption,setselecthostingOption] = useState([]);

console.log(selecthostingOption);


const hostingChange = (e) => {
  e.preventDefault();
  const value = e.target.value
  setselecthostingOption(selecthostingOption => [
    ...selecthostingOption,value
  ])

}   
return(
<>
   <button onClick={hostingChange} name="selecthostingOption" value="1">Click 1</button>
   <button onClick={hostingChange} name="selecthostingOption" value="2">Click 2</button>

</>
)
}

Upvotes: 1

Views: 453

Answers (2)

mzedeler
mzedeler

Reputation: 4369

Don't use an array for something like this. Use an object:

import React, { useState } from 'react'; 

const UserDetails = () => {
  const [hostingOptions, setHostingOptions] = useState({});

  const hostingChange = (e) => {
    e.preventDefault()
    const value = e.target.value
    setHostingOptions(!!hostingOptions[value])
  }

  return(
    <>
      <button onClick={hostingChange} name="selecthostingOption" value="1">Click 1</button>
      <button onClick={hostingChange} name="selecthostingOption" value="2">Click 2</button>
    </>
  )
}

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Check the value if already in selections,

const hostingChange = e => {
  e.preventDefault();
  const value = e.target.value;

  if (selecthostingOption.includes(value)) {
    setselecthostingOption(selecthostingOption.filter(x => x !== value));
  } else {
    setselecthostingOption([...selecthostingOption, value]);
  }
};

Change both button styles based on selections

<button onClick={hostingChange} name="selecthostingOption" style={{
    color: selecthostingOption.includes("1") 'red' : ''
  }} value="1">Click 1</button>

Upvotes: 1

Related Questions