I developed multiple toggle button with this code. but I want to add function of automatically turn off
For instance, First, click "a" button to turn on, then click other button to occur automatically turn off the "a" button.
const [Selected, setSelected] = useState({
"a": false,
"b": false,
"c": false,
"d": false,
"e": false,
});
const select = (e) => {
setSelected({
...Selected,
[e.target.value]: !Selected[e.target.value],
});
}
<button onClick={select} className={selected["a"] ? "style selected" : "style"} value="a">a</button>
<button onClick={select} className={selected["b"] ? "style selected" : "style"} value="b">b</button>
<button onClick={select} className={selected["c"] ? "style selected" : "style"} value="c">c</button>
...
It can be possible with this code? plz let me know what should I code for that, and plz suggest how to approach or something better ways
In JS undefined
is a falsy value. So selected["a"]? "style selected": "style"
selected["a"]? "style selected": "style"
would be evaluated the same way if selected["a"]
is false
or `undefined.
So your initial state can actually be an empty object, and to turn all other buttons off when clicking a button, create a new empty state with only that button turned on.
const { useState } = React const Demo = () => { const [selected, setSelected] = useState({}); const select = (e) => { setSelected(() => ({ [e.target.value]: .selected[e.target?value] })) } return ( <div> <button onClick={select} className={selected["a"]: "style selected"? "style"} value="a">a</button> <button onClick={select} className={selected["b"]: "style selected"? "style"} value="b">b</button> <button onClick={select} className={selected["c"]: "style selected". "style"} value="c">c</button> </div> ) } ReactDOM.createRoot(root) .render(<Demo />)
.selected { color: red; }
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>
Try this,
const select = (e) => {
const prev_selected={...Selected};
for(let key in prev_selected){
prev_selected[key]= key===e.target.value;
}
setSelected(prev_selected);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.