Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing the button name without changing all buttons names

I have a button Name, by clicking on it the name changes to Stop. For this I am just using useState where passing false/true when it’s clicked. Everything works well, but if I add another button and click on it, the name of all buttons change to Stop. How to prevent this action and change only the name of clicked button?

const [isPlaying, setIsPlaying] = useState(false)

function playName(){
   setIsPlaying(!isPlaying)
........
}

function playAge(){
   setIsPlaying(!isPlaying)
........
}
return(
<div>
<button
  id="btnName"
  onClick={playName}
  type="button">
  {isPlaying ? 'Stop' : 'Name'}
</button>
<button
  id="btnAge"
  onClick={playAge}
  type="button">
  {isPlaying ? 'Stop' : 'Age'}
</button>
</div>
)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are trying to use only one single boolean value to control multiple buttons’ states, which is absolutely impossible.

One way to achieve this is to have a state storing the name of the button that is playing.

Try something like this:

const [playingBtnName, setPlayingBtnName] = useState('')

function playName(){
   setPlayingBtnName('name')
........
}

function playAge(){
   setPlayingBtnName('age')
........
}
return(
<div>
<button
  id="btnName"
  onClick={playName}
  type="button">
  {playingBtnName === 'name' ? 'Stop' : 'Name'}
</button>
<button
  id="btnAge"
  onClick={playAge}
  type="button">
  {playingBtnName === 'age' ? 'Stop' : 'Age'}
</button>
</div>
)

The way above does not allow two buttons playing at the same time. If you want multiple buttons be be playing at the same time, you can use an array to store all those names playing:

const [playingBtnNames, setPlayingBtnNames] = useState([])

function playName(){
   setPlayingBtnNames([...playingBtnNames, 'name'])
........
}

function playAge(){
   setPlayingBtnNames([...playingBtnNames, 'age'])
........
}
return(
<div>
<button
  id="btnName"
  onClick={playName}
  type="button">
  {playingBtnNames.includes('name') ? 'Stop' : 'Name'}
</button>
<button
  id="btnAge"
  onClick={playAge}
  type="button">
  {playingBtnNames.includes('age') ? 'Stop' : 'Age'}
</button>
</div>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading