How to create a Material ui checkbox which when checked will disable Textfield and fixed the alignment?
Link to sandbox:
https://codesandbox.io/s/material-demo-forked-mfnqk?file=/demo.tsx
You should utilize the List component provided by Material UI. Give it the alignItems="center" prop to fix the alignment. Then, the Material UI Checkboxes component accepts a boolean for the disabled prop so you should have that set to the value of 'checked' in your state hooks. That way, when 'checked' is updated, the disabled prop updates as well. I also added a fullWidth prop to the textField to make it less cluttered. A live demo can be found here, but here's how I worked it out:
import React from "react";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import Typography from "@material-ui/core/Typography";
export default function Checkboxes() {
const [checked, setChecked] = React.useState(false);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked(event.target.checked);
};
return (
<>
<List>
<ListItem alignItems="center">
<Checkbox
checked={checked}
onChange={handleChange}
inputProps={{ "aria-label": "primary checkbox" }}
/>
<TextField
fullWidth
disabled={checked}
label="disable when checkbox checked"
/>
</ListItem>
<ListItem alignItems="center">
<Typography variant="subtitle1" style={{ marginRight: "3px" }}>
Hello
</Typography>
<TextField
fullWidth
disabled={!checked}
label="enable when checkbox checked"
/>
</ListItem>
</List>
</>
);
}