Categories
React Answers

How to handle change on Autocomplete component from React Material UI?

Sometimes, we want to handle change on Autocomplete component from React Material UI.

In this article, we’ll look at how to handle change on Autocomplete component from React Material UI.

How to handle change on Autocomplete component from React Material UI?

To handle change on Autocomplete component from React Material UI, we set the onChange prop of the Autocomplete to a function that has the value as the 2nd parameter.

And we can set the value prop to the state that we called the state setter function to set the value for.

For instance, we write:

import React, { useState } from "react";
import { TextField } from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";

const top5Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 }
];

export default function App() {
  const [movie, setMovie] = useState(top5Films[0]);

  return (
    <div>
      <Autocomplete
        value={movie}
        options={top5Films}
        getOptionLabel={(option) => option.title}
        onChange={(event, value) => setMovie(value)}
        renderInput={(params) => (
          <TextField {...params} label="Label" variant="outlined" fullWidth />
        )}
      />
    </div>
  );
}

We have the top5films array which we use as the value of the options prop.

And we set the value to the movie state to show the selected value.

Next, we set the getOptionLabel to a function that returns the property value to show in the top5Films array.

Then we set the onChange prop to a function that calls setMovie with value to set movie to the selected option.

Finally, we set the renderInput to a function that renders a TextField to render the text field.

As a result, we see that ‘The Shawshank Redemption’ is set initially.

And when we select another choice, we see the selected choice displayed.

Conclusion

To handle change on Autocomplete component from React Material UI, we set the onChange prop of the Autocomplete to a function that has the value as the 2nd parameter.

And we can set the value prop to the state that we called the state setter function to set the value for.

Categories
React Answers

How to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component?

Sometimes, we need to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component.

In this article, we’ll look at how to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component.

How to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component?

To fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component, we can set the default value for the value prop.

For instance, we write:

import React, { useState } from "react";
import { FormControl, InputLabel, Select, MenuItem } from "@material-ui/core";

export default function App() {
  const [age, setAge] = useState();

  return (
    <div>
      <FormControl fullWidth>
        <InputLabel>Age</InputLabel>
        <Select
          value={age ?? 10}
          label="Age"
          onChange={(e) => setAge(e.target.value)}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

We set the value prop of the Select component to the age state.

And we set the value to 10 if age is undefined.

Next, we add the onChange prop and set it to a function to set the age state to the selected value.

And we add some MenuItems inside the Select component to add some choices.

Conclusion

To fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component, we can set the default value for the value prop.

Categories
React Answers

How to customize the color of a checkbox in React Material UI?

Sometimes, we want to customize the color of a checkbox in React Material UI.

In this article, we’ll look at how to customize the color of a checkbox in React Material UI.

How to customize the color of a checkbox in React Material UI?

To customize the color of a checkbox in React Material UI, we can set the style prop to an object with the color we want.

For instance, we write:

import React, { useState } from "react";
import { Checkbox, FormControlLabel, Typography } from "@material-ui/core";

export default function App() {
  const [val, setVal] = useState(false);

  return (
    <div>
      <FormControlLabel
        control={
          <Checkbox
            checked={val}
            onChange={(e) => setVal(e.target.checked)}
            style={{
              color: "#00e676"
            }}
            value="work"
          />
        }
        label={
          <Typography variant="h6" style={{ color: "#2979ff" }}>
            Work
          </Typography>
        }
      />
    </div>
  );
}

We set the style prop of the Checkbox to an object with the color of the checkbox.

Next, we set the label color by setting the style prop to an object with the color of the label.

Conclusion

To customize the color of a checkbox in React Material UI, we can set the style prop to an object with the color we want.

Categories
React Answers

How to add form validation with React and Material UI?

Sometimes, we want to add form validation with React and Material UI.

In this article, we’ll look at how to add form validation with React and Material UI.

How to add form validation with React and Material UI?

To add form validation with React and Material UI, we can set the error prop of the TextField to show the error state when there’s an error.

We can set the helperText prop to show the error message.

For instance, we write:

import React, { useState } from "react";
import { TextField } from "@material-ui/core";

export default function App() {
  const [text, setText] = useState();

  return (
    <div>
      <TextField
        value={text}
        onChange={(event) => setText(event.target.value)}
        error={text === ""}
        helperText={text === "" ? "Empty!" : " "}
      />
    </div>
  );
}

We add a TextField with the value prop set to text to show the inputted text.

And we set the onChange prop to a function that calls setText to set the inputted value as the value of the text prop.

Next, we set the error prop to text === "" to make the input box red when text is an empty string.

Finally, we set the helperText to text === "" ? "Empty!" : " " to check if text is an empty string.

If it is, then we show ‘Empty!`. Otherwise, we show nothing.

Conclusion

To add form validation with React and Material UI, we can set the error prop of the TextField to show the error state when there’s an error.

We can set the helperText prop to show the error message.

Categories
React Answers

How to use CSS child selectors in React Material UI?

Sometimes, we want to use CSS child selectors in React Material UI.

In this article, we’ll look at how to use CSS child selectors in React Material UI.

How to use CSS child selectors in React Material UI?

To use CSS child selectors in React Material UI, we can start the property names of the style properties with &.

For instance, we write:

import React, { useState } from "react";
import {
  makeStyles,
  Paper,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody
} from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    marginTop: theme.spacing.unit * 3,
    overflowX: "auto"
  },
  table: {
    minWidth: 700
  },
  deleted: {
    "& td": {
      background: "red"
    }
  }
}));

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const rows = [
  createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
  createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
  createData("Eclair", 262, 16.0, 24, 6.0),
  createData("Cupcake", 305, 3.7, 67, 4.3),
  createData("Gingerbread", 356, 16.0, 49, 3.9)
];

export default function App() {
  const classes = useStyles();

  return (
    <div>
      <Paper className={classes.root}>
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell align="right">Calories</TableCell>
              <TableCell align="right">Fat (g)</TableCell>
              <TableCell align="right">Carbs (g)</TableCell>
              <TableCell align="right">Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row) => {
              return (
                <TableRow key={row.id} className={classes.deleted}>
                  <TableCell component="th" scope="row">
                    {row.name}
                  </TableCell>
                  <TableCell align="right">{row.calories}</TableCell>
                  <TableCell align="right">{row.fat}</TableCell>
                  <TableCell align="right">{row.carbs}</TableCell>
                  <TableCell align="right">{row.protein}</TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </Paper>
    </div>
  );
}

We have the deleted class styles for the td elements that are in the child of the selector.

We add this with '& td'.

And we set the background to red.

In App, we call useStyles to return the classes.

And we set the className to classes.deleted to TableRow.

As a result, the td elements have the background red since we select the td elements inside the element with class deleted and style them to have a red background.

Conclusion

To use CSS child selectors in React Material UI, we can start the property names of the style properties with &.