How to Style label on MUI Radio Button when checked - javascript

Good day everyone I'm trying to style the label text on the radio button to change to a blue color when selected.
THIS IS MY CODE OF THE MUI BUTTON SO FAR
import * as React from "react";
import Radio from "#mui/material/Radio";
import RadioGroup from "#mui/material/RadioGroup";
import FormControlLabel from "#mui/material/FormControlLabel";
import FormControl from "#mui/material/FormControl";
export default function RowRadioButtonsGroup({label1, label2}) {
return (
<FormControl>
<RadioGroup
row
aria-labelledby="demo-row-radio-buttons-group-label"
name="row-radio-buttons-group"
style={{display: 'flex', gap: '2rem'}}
sx={{
'& .MuiSvgIcon-root': {
fontSize: 28,
},
}}
>
<FormControlLabel value="Sunday" control={<Radio />} label={label1}/>
<FormControlLabel value="Monday" control={<Radio />} label={label2} />
</RadioGroup>
</FormControl>
);
}

Basically just create a styled form control label and use "useRadioGroup " hook button and choose the colors for checked and unchecked
https://codesandbox.io/s/radiobuttonsgroup-demo-material-ui-forked-pix9rg?file=/demo.js
// Custom label
const StyledFormControlLabel = styled((props) => (
<FormControlLabel {...props} />
))(({ theme, checked }) => ({
".MuiFormControlLabel-label": checked && {
// Change color here
color: "red"
}
}));
// Custom FormControl
function MyFormControlLabel(props) {
// MUI UseRadio Group
const radioGroup = useRadioGroup();
let checked = false;
if (radioGroup) {
checked = radioGroup.value === props.value;
}
return <StyledFormControlLabel checked={checked} {...props} />;
}
<MyFormControlLabel value="female" control={<Radio />} label="Female" />

Related

ReactJS TypeScript MUI TextField set value using useSate and add onchange event function for text filed

I am new to ReactJS with MUI development, have below ReactJS TypeScript with MuiText filed form. Looking some help to use useSate method to change the textfiled value.
Also add the onchnage function for the text filed. I can add the onchange function for normal text filed, unsure how to add it for MUI Text filed?
import * as React from 'react';
import { useState } from "react"
import Button from '#mui/material/Button';
import CssBaseline from '#mui/material/CssBaseline';
import TextField from '#mui/material/TextField';
import Grid from '#mui/material/Grid';
import Box from '#mui/material/Box';
import Container from '#mui/material/Container';
import { createTheme, ThemeProvider } from '#mui/material/styles';
import { useForm, SubmitHandler, Controller } from 'react-hook-form';
import * as yup from 'yup';
import { yupResolver } from '#hookform/resolvers/yup';
interface IFormInputs {
filepath: string;
}
const schema = yup.object().shape({
filepath: yup.string().min(4).required(),
});
const theme = createTheme();
export default function MuiTextField() {
const {
control,
handleSubmit,
formState: { errors },
} = useForm<IFormInputs>({
resolver: yupResolver(schema),
});
const [filepath, setFilepath] = useState("vodeo.mp3");
const onSubmit: SubmitHandler<IFormInputs> = (data) => {
console.log('data submitted: ', data);
console.log('filepath: ', data.filepath);
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="lg">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<form onSubmit={handleSubmit(onSubmit)}>
<Box sx={{ mt: 3 }}>
<Grid container spacing={2}>
<Grid item xs={16} sm={6}>
<Controller
name="filepath"
control={control}
defaultValue=""
render={({ field }) => (
<TextField
{...field}
label="File Path"
error={!!errors.filepath}
helperText={errors.filepath ? errors.filepath?.message : ''}
autoComplete="file-path"
fullWidth
/>
)}
/>
</Grid>
<Button
type="submit"
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Submit
</Button>
</Grid>
</Box>
</form>
</Box>
</Container>
</ThemeProvider>
);
}
Update:
Here is the codeshare: https://codesandbox.io/s/boring-water-m47uxn?file=/src/App.tsx
When we change the text box value to auto, want to change the textbox value to audio.mp3. but its not working.
MUI Textfield have onChange too:
<TextField
error={Boolean(touched.name && errors.name)}
fullWidth
label={t('Name')}
name="name"
onBlur={handleBlur}
onChange={handleChange}
value={values.name}
variant="outlined"
autoComplete="off"
/>
'field' in render function contains onChange.
And state of form saved in useForm. In useForm props you have to add defaultValues. And you did not pass prop type="file", maybe its your problem.
Guide about create file input with react hook form: https://refine.dev/blog/how-to-multipart-file-upload-with-react-hook-form/
Textfield api: https://mui.com/material-ui/api/text-field/

Material UI 5 Indeterminate checkbox doesn't work properly

I'm trying to add more children to the parent checkbox in the FormControlLabel.
Everything is working properly, however, the third child doesn't work properly. I want it to work as the Material UI Example
Here is my code
import * as React from "react";
import Box from "#mui/material/Box";
import Checkbox from "#mui/material/Checkbox";
import FormControlLabel from "#mui/material/FormControlLabel";
export default function IndeterminateCheckbox() {
const [checked, setChecked] = React.useState([true, false, false]);
const handleChange1 = (event) => {
setChecked([
event.target.checked,
event.target.checked,
event.target.checked
]);
};
const handleChange2 = (event) => {
setChecked([event.target.checked, checked[1], checked[2]]);
console.log(checked, "first");
};
const handleChange3 = (event) => {
setChecked([checked[0], event.target.checked, checked[2]]);
console.log(checked, "second");
};
const handleChange4 = (event) => {
setChecked([checked[0], event.target.checked, checked[1]]);
console.log(checked, "third");
};
const children = (
<Box sx={{ display: "flex", flexDirection: "column", ml: 3 }}>
<FormControlLabel
label="Child 1"
control={<Checkbox checked={checked[0]} onChange={handleChange2} />}
/>
<FormControlLabel
label="Child 2"
control={<Checkbox checked={checked[1]} onChange={handleChange3} />}
/>
<FormControlLabel
label="Child 3"
control={<Checkbox checked={checked[2]} onChange={handleChange4} />}
/>
</Box>
);
return (
<div>
<FormControlLabel
label="Parent"
control={
<Checkbox
checked={checked[0] && checked[1] && checked[2]}
indeterminate={checked[0] !== checked[1] && checked[2]}
onChange={handleChange1}
/>
}
/>
{children}
</div>
);
}
Any advice would be greatly appreciated, I am new to Material UI and react so please excuse any syntax problems.
Thank you!

Multilevel drop downs with checkboxes in React

I want to create nested dropdowns with each having checkboxes in them like this:
Is there a way to do this in react. Couldn't find a way to implement this with any specific library
You can create a nested dropdown with checkboxes with material ui
Here's the link you can view:
https://mui.com/components/checkboxes/
And here's the source code from material UI to achieve the result:
import * as React from 'react';
import Box from '#mui/material/Box';
import Checkbox from '#mui/material/Checkbox';
import FormControlLabel from '#mui/material/FormControlLabel';
export default function IndeterminateCheckbox() {
const [checked, setChecked] = React.useState([true, false]);
const handleChange1 = (event) => {
setChecked([event.target.checked, event.target.checked]);
};
const handleChange2 = (event) => {
setChecked([event.target.checked, checked[1]]);
};
const handleChange3 = (event) => {
setChecked([checked[0], event.target.checked]);
};
const children = (
<Box sx={{ display: 'flex', flexDirection: 'column', ml: 3 }}>
<FormControlLabel
label="Child 1"
control={<Checkbox checked={checked[0]} onChange={handleChange2} />}
/>
<FormControlLabel
label="Child 2"
control={<Checkbox checked={checked[1]} onChange={handleChange3} />}
/>
</Box>
);
return (
<div>
<FormControlLabel
label="Parent"
control={
<Checkbox
checked={checked[0] && checked[1]}
indeterminate={checked[0] !== checked[1]}
onChange={handleChange1}
/>
}
/>
{children}
</div>
);
}
Here's the codesandbox link where I have combined the material UI component with the checkboxes.
https://codesandbox.io/s/indeterminatecheckbox-material-demo-forked-o0vvw?file=/demo.js:0-2222

How to setup form with multiple Checkboxes which only one can be "checked" with Material-UI components?

I want to build simple form using Material-UI which has:
multiple options, checkboxes
only one option can be true, checked
And then, basing on which option is checked I want to push certain information to my formData and send it to my backend on handleSubmit
My Form component looks like this:
const MyFormComponent= () => {
const [formData, setFormData] = useState({ reason: "", feedback: ""});
const [checkboxesState, setCheckboxesState] = useState({
one: false,
two: false,
three: false
})
const handleSubmit = (e) => {
/* ... */
};
const handleChange = (e) => {
/* ... */
}
return (
<>
<form onSubmit={handleSubmit}>
<Grid container>
<FormLabel component="legend"> Some asked question here? </FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox checked={checkboxesState.one} color="primary" onChange={handleChange} name="one" />}
label="Label for my first checkbox"
/>
<FormControlLabel
control={<Checkbox checked={checkboxesState.two} color="primary" onChange={handleChange} name="two" />}
label="Label for my secound checkbox"
/>
<FormControlLabel
control={<Checkbox checked={checkboxesState.three} color="primary" onChange={handleChange} name="three" />}
label="Label for my third checkbox"
/>
</FormGroup>
</Grid>
<ButtonWrapper>
<Button variant="outlined" color="secondary" type="submit"> Delete </Button>
<Button variant="contained" color="primary"> Go back </Button>
</ButtonWrapper>
</form>
</>
);
}
So I came up with solution on my handleChange like this, works perfectly fine, but I will have to create another if(/* */) else if(/* */) else if(/* */) instruction on my handleSubmit.
I believe there is much more elegant solution based on Material-UI components API which I don't know yet or don't know how to use it. Can someone suggest me something else in this situation?
const handleChange = (e) => {
if(e.target.name === "one") {
setCheckboxesState({
one: e.target.checked,
two: false,
three: false
});
} else if (e.target.name === "two") {
setCheckboxesState({
one: false,
two: e.target.checked,
three: false
});
} else if (e.target.name === "three") {
setCheckboxesState({
one: false,
two: false,
three: e.target.checked
});
}
}
If you want to achieve "Multiple options, only one selected", Radio Buttons is a better UX choice for that scenario.
Quoting from https://www.nngroup.com/articles/checkboxes-vs-radio-buttons/
Radio buttons are used when there is a list of two or more options
that are mutually exclusive and the user must select exactly one
choice. In other words, clicking a non-selected radio button will
deselect whatever other button was previously selected in the list.
Checkboxes are used when there are lists of options and the user may
select any number of choices, including zero, one, or several. In
other words, each checkbox is independent of all other checkboxes in
the list, so checking one box doesn't uncheck the others.
To achieve Radio group using Material UI, please refer to Material UI docs. They have excellent examples.
import React from 'react';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
export default function RadioButtonsGroup() {
const [value, setValue] = React.useState('female');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup aria-label="gender" name="gender1" value={value} onChange={handleChange}>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
<FormControlLabel value="other" control={<Radio />} label="Other" />
<FormControlLabel value="disabled" disabled control={<Radio />} label="(Disabled option)" />
</RadioGroup>
</FormControl>
);
}
You could track the current select checkbox with one variable instead of multiple.
const MyFormComponent= () => {
const [formData, setFormData] = useState({ reason: "", feedback: ""});
const [checkboxesState, setCheckboxesState] = useState(-1)
const handleSubmit = (e) => {
/* ... */
};
const handleChange = (e) => {
setCheckboxesState(e.target.name);
}
return (
<>
<form onSubmit={handleSubmit}>
<Grid container>
<FormLabel component="legend"> Some asked question here? </FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox checked={checkboxesState === 0} color="primary" onChange={handleChange} name={0} />}
label="Label for my first checkbox"
/>
<FormControlLabel
control={<Checkbox checked={checkboxesState === 1} color="primary" onChange={handleChange} name={1} />}
label="Label for my secound checkbox"
/>
<FormControlLabel
control={<Checkbox checked={checkboxesState === 2} color="primary" onChange={handleChange} name={2} />}
label="Label for my third checkbox"
/>
</FormGroup>
</Grid>
<ButtonWrapper>
<Button variant="outlined" color="secondary" type="submit"> Delete </Button>
<Button variant="contained" color="primary"> Go back </Button>
</ButtonWrapper>
</form>
</>
);
}

Reactjs - material-ui radiobuttons with FormControlLabel - not working

I am trying to use the radio buttons from material-ui - https://material-ui.com/components/radio-buttons/
Although the example here doesn't provide the selected radio button on submitting the form. I am also trying to use redux-forms - https://redux-form.com/6.0.0-rc.4/examples/material-ui/ but their documentation seems out of date. I am not sure how you would pre-select a radio button for example.
renderRadioGroup.js
import React from 'react';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
const renderRadioGroup = ({ input, label, value, fieldName, handleChange, options, meta: { touched, error }}) => (
<FormControl component="fieldset" fullWidth={true}>
<FormLabel component="legend">{label} {value}</FormLabel>
<RadioGroup
row
aria-label={fieldName}
name={fieldName}
value={value}
onChange={handleChange}
>
{
options.map((item, j) =>
<FormControlLabel key={j} value={item.value} disabled={item.disabled} control={<Radio />} label={item.label} />
)
}
</RadioGroup>
</FormControl>
)
export default renderRadioGroup;
shell
<Field
name="paymentplan"
component={renderRadioGroup}
label="Do you wish to pay monthly or annually?"
value={"1"}
fieldName="paymentplan"
options={
[
{
"label" : "Monthly",
"value" : "0"
},
{
"label" : "Annually",
"value" : "1"
}
]
}
/>

Categories