I am trying to create a Raidobutton in React. Below is the code.
When I click on first radio button("Windows") , the Radiobutton shows checked, when I click second one ("Mac") the Radiobutton does not show checked even though the checked is true. When we again click on "Mac" Radiobutton gets checked.And after that all Radiobutton works fine.
Can somebody help with this.
import './App.css';
import { useState } from 'react';
const options = ["Windows", "Mac", "Linux"]
const days = ["Male", "Female"]
const TempRadio = ({ item, group }) => {
const [checked, setChecked] = useState('')
const handleChnage = (e) => {
console.log(e.target.value)
setChecked(() => e.target.value)
}
return (
<label>
<input type="radio" value={item} checked={item === checked} name={group} onChange={ handleChnage} />{item}
</label>
)
}
function App() {
const renderItems = (items, group) => {
return <div className='myul'>{items.map((item) =>
<TempRadio item={item} key={item} group={group} />
)}</div>
}
return (
<div className="App">
<header className="App-header">
<h1>
Which OS?
</h1>
{renderItems(options, "OS")}
<h2>Gender</h2>
{renderItems(days, "time")}
</header>
</div>
);
}
export default App;
2
Answers
You are creating radio buttons the wrong way. Beacuse you give each one it’s own state it will not work:
What you need is something like this:
Since you’re grouping radio buttons, and you’ll probably want to do "something" with the output from both sets, it makes sense to shift the responsibility of state management to the parent component (in this case
App
).So in
app
the state is an object that uses thegroup
value as a key, and the value of the clicked radio button as its value.In this example I’ve create a
RadioGroup
component to help manage the flow of data. The respective options get passed down here, as well as the group label, the group name, the state for that group, and the shared handler.(The
useEffect
is temporary – it just shows how the state is updated when the buttons are changed within each radio group. I also relabelled yourdays
/time
variable as it didn’t seem to relate to the actual content – gender.)