1

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>

</>
)
}

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

how to make it dynamic please. Like selecthostingOption.includes("1") in this line, can i make it dynamic instead of static includes. @Siva Kondapi Venkata
@AdnanArif, Yes, you can do that. like ['1', '2'].map(id => (<button onClick={hostingChange} name="selecthostingOption" style={{ color: selecthostingOption.includes(id) 'red' : '' }} value={id}>Click ${id}</button>)`
0

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>
    </>
  )
}

2 Comments

Then how I will get all values from same name options.
In your example, they have different values (1 and 2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.