Reactjs Material-UI radio buttons component
YouTube video:
I have published one video on YouTube. You can watch it here to learn more on it:
How to import:
Radio component is defined in @material-ui/core and you can import it as like below:
import { Radio } from '@material-ui/core';
Simple example of Radio:
Let's take a look at the below example:
import { Radio } from '@material-ui/core';import React from 'react';function App() {return (<div style={{ marginTop: 40, marginLeft: 100 }}><Radio checked={true} value="one" /><Radio checked={true} value="two" /><Radio checked={false} value="three" /><Radio checked={true} value="four" /></div>);}export default App;
Here, we are loading four Radio buttons. checked is used to define if the Radio is checked or not. value is value of the component.
If you run this, it will load the below screen:
Adding click listener to Radio:
We can add a click listener to radio buttons and based on that, it will check/uncheck:
import { Radio } from '@material-ui/core';import React, { useState } from 'react';function App() {const [selected, setSelected] = useState('');const selectionChangeHandler = (event) => {setSelected(event.target.value);};return (<div style={{ marginTop: 40, marginLeft: 100 }}><Radio onChange={selectionChangeHandler} checked={selected == 'one'} value="one" /><Radio onChange={selectionChangeHandler} checked={selected == 'two'} value="two" /><Radio onChange={selectionChangeHandler} checked={selected == 'three'} value="three" /><Radio onChange={selectionChangeHandler} checked={selected == 'four'} value="four" /></div>);}export default App;
onChange is called on clicking a radio button and it changes the selected value. Based on its value, the checked/unchecked of radio button is changed.
Using radio group with FormControl:
Radio buttons can be easily integrated with FormControl and RadioGroup:
import { Radio, FormControl, RadioGroup, FormControlLabel } from '@material-ui/core';import React, { useState } from 'react';function App() {const [selected, setSelected] = useState('');const selectionChangeHandler = (event) => {setSelected(event.target.value);};return (<FormControl><RadioGroup row value={selected} onChange={selectionChangeHandler}><FormControlLabel value="first" control={<Radio />} label="First Selection" /><FormControlLabel value="second" control={<Radio />} label="Second Selection" /><FormControlLabel value="third" control={<Radio />} label="Third Selection" /></RadioGroup></FormControl>);}export default App;