Working with radio in React
Working with radio
radio
is a bit different from, for example, the same checkboxes. The problem is that several radios will have the same state, but different value
.
Therefore, the work is done as follows: each radio button has its own value written into the value
attribute, and a special condition is written into the checked
attribute, which checks whether the state is equal to a certain value. If it is equal, the radio button will be checked, and if it is not, it will be unchecked.
Here is the implementation of what was described:
function App() {
const [value, setValue] = useState(1);
function changeHandler(event) {
setValue(event.target.value);
}
return <div>
<input
type="radio"
name="radio"
value="1"
checked={value === '1' ? true : false}
onChange={changeHandler}
/>
<input
type="radio"
name="radio"
value="2"
checked={value === '2' ? true : false}
onChange={changeHandler}
/>
<input
type="radio"
name="radio"
value="3"
checked={value === '3' ? true : false}
onChange={changeHandler}
/>
</div>
}
Given 3
radio buttons. Given a paragraph. Make the value of the selected radio button appear in this paragraph.
Use radio buttons to ask the user for their favorite programming language. Display their choice in a paragraph. If JavaScript is chosen, praise the user.