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