Hi everyone, Using ReactJs, I want to change the text and style of these 5 button when each of them is clicked.
i.e:
- if button 1 is clicked change text and button background
- if button 2 is clicked too, change text and button background
- if button 3 is clicked too, change text and button background too
…and so on
These buttons are displayed after mapping through a data like the example below
import react from 'react'
const buttons = [1, 2, 3,4,5];
const ActiveButtons = () => {
return (
{buttons.map((btn, i) => {
return <button key={i}>Click me</button>
})}
)
}
export default ActiveButtons
Hi @adefesoq, you can have your ActiveButtons component maintain a state of active buttons:
function ActiveButtons () {
const [active, setActive] = useState([])
const buttons = [1, 2, 3, 4, 5]
return buttons.map(key => {
const isActive = active.includes(key)
return (
<button
key={key}
onClick={() => !isActive && setActive([...active, key])}
style={{ background: isActive ? 'red' : 'white' }}
>
Button {key}
</button>
)
})
}
Or to toggle the active state:
function ActiveButtons () {
const [active, setActive] = useState([])
const buttons = [1, 2, 3, 4, 5]
return buttons.map(key => {
const isActive = active.includes(key)
return (
<button
key={key}
onClick={() => setActive(isActive
? active.filter(current => current !== key)
: [...active, key]
)}
style={{ background: isActive ? 'red' : 'white' }}
>
Button {key}
</button>
)
})
}
Thank you @m3g4p0p but the toggle active state code doesn’t work (toggle) on my end here.
Can you please have a look at the code
Have you imported useState?
import React, { useState } from 'react';
(from the State page linked in mega’s post)
1 Like
Ah yes, thanks @m_hutley!
@adefesoq here’s a working sandbox:
It’s a great help. Thank you for your information.
Thank you @m3g4p0p @m_hutley I have a working code now
1 Like
system
Closed
8
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.