Categories
React Answers

How to set the card height with React Material UI?

Sometimes, we want to set the card height with React Material UI.

In this article, we’ll look at how to set the card height with React Material UI.

How to set the card height with React Material UI?

To set the card height with React Material UI, we can set the style prop of the Card.

For instance, we write:

import React from "react";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";

const cardStyle = {
  display: "block",
  transitionDuration: "0.3s",
  height: "45vw"
};

export default function App() {
  return (
    <div>
      <Card style={cardStyle}>
        <CardHeader
          title="URL Avatar"
          subtitle="Subtitle"
          avatar="https://placeimg.com/800/450/nature"
        />
      </Card>
    </div>
  );
}

to set the style prop of the Card to an object that has the height of the card.

As a result, the card height should be set to 45vw.

Conclusion

To set the card height with React Material UI, we can set the style prop of the Card.

Categories
React Answers

How to use React Material UI’s Autocomplete component with Formik?

Sometimes, we want to use React Material UI’s Autocomplete component with Formik.

In this article, we’ll look at how to use React Material UI’s Autocomplete component with Formik.

How to use React Material UI’s Autocomplete component with Formik?

To use React Material UI’s Autocomplete component with Formik, we can call Formik’s setFieldValue function with the name prop value of the Autocomplete and the value that is selected.

For instance, we write:

import React from "react";
import { Formik, Form } from "formik";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import Button from "@material-ui/core/Button";

const cities = [
  { name: "New York", value: 1, state: "NY" },
  { name: "San Francisco", value: 2, state: "CA" },
  { name: "Los Angeles", value: 3, state: "CA" }
];

export default function App() {
  return (
    <div>
      <Formik
        initialValues={{ cityId: 1 }}
        onSubmit={({ cityId }) => {
          console.log(cityId);
        }}
      >
        {({ handleChange, values, setFieldValue }) => (
          <Form>
            <Autocomplete
              id="cityId"
              name="cityId"
              options={cities}
              groupBy={(option) => option.state}
              getOptionLabel={(option) => option.name}
              style={{ width: 300 }}
              onChange={(event, value) => {
                setFieldValue("cityId", value.value);
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  onChange={handleChange}
                  margin="normal"
                  label="Cities"
                  fullWidth
                  value={values?.cityId}
                />
              )}
            />

            <Button variant="contained" color="primary" type="submit">
              Submit
            </Button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

We add the Form component with the Autocomplete component inside.

We set the onChange prop of the Autocomplete to a function that calls setFieldValue with the Autocomplete‘s name prop’s value and the value parameter.

The value parameter has the whole object that’s selected from cities.

Next, we set the getOptionLabel prop to return the property value to display in the options.

And we set the value prop of the TextField to the values?.cityId property to display the selected choice.

Then we set the onSubmit prop of the Formik component to a function that takes the object with submitted values as the parameter and logs the selected value.

As a result, when we select an item and click Submit, we see that the cityId value is set to the value property of the cities entry that’s selected.

Conclusion

To use React Material UI’s Autocomplete component with Formik, we can call Formik’s setFieldValue function with the name prop value of the Autocomplete and the value that is selected.

Categories
React Answers

How to invalidate a TextField in React Material UI?

Sometimes, we want to invalidate a TextField in React Material UI.

In this article, we’ll look at how to invalidate a TextField in React Material UI.

How to invalidate a TextField in React Material UI?

To invalidate a TextField in React Material UI, we set the error and helperText props of the TextField to display the error message we want.

For instance, we write:

import React from "react";
import TextField from "@material-ui/core/TextField";

const phoneRegex = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;

export default function App() {
  const [errorText, setErrorText] = React.useState();
  const [phone, setPhone] = React.useState();

  const onChange = (event) => {
    if (event.target.value.match(phoneRegex)) {
      setErrorText("");
      setPhone(event.target.value);
    } else {
      setErrorText("invalid format");
    }
  };

  return (
    <div>
      <TextField
        label="Phone"
        name="phone"
        helperText={errorText}
        error={errorText}
        onChange={onChange}
        value={phone}
      />
    </div>
  );
}

We set the error prop to make the TextField‘s border red when we enter invalid input.

And we set the helperText prop to display the error text at the bottom.

We set the onChange prop to the onChange function.

It checks whether the ionputted value matches the pattern in the phoneRegex by calling event.target.value.match.

We call setErrorText to set the errorText to set the error message if needed.

And we call setPhone to set the phone state which we use as the value of the TextField‘s value prop to display the inputted value.

Therefore, when we enter invalid text, we see that the text field has a red border.

Conclusion

To invalidate a TextField in React Material UI, we set the error and helperText props of the TextField to display the error message we want.

Categories
React Answers

How to submit the form that is inside a dialog using React Material UI?

Sometimes, we want to submit the form that is inside a dialog using React Material UI.

In this article, we’ll look at how to submit the form that is inside a dialog using React Material UI.

How to submit the form that is inside a dialog using React Material UI?

To submit the form that is inside a dialog using React Material UI, we can put a form element inside the dialog and add a input with type submit inside the form.

For instance, we write:

import React from "react";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import TextField from "@material-ui/core/TextField";

export default function App() {
  const [staffNumber, setStaffNumber] = React.useState();
  const [open, setOpen] = React.useState(false);
  const handleCreate = (e) => {
    e.preventDefault();
    console.log(staffNumber);
    setStaffNumber("");
    setOpen(false);
  };

  return (
    <div>
      <Button onClick={() => setOpen(true)}>open</Button>
      <Dialog title="Dialog" open={open}>
        <DialogContent>
          <form onSubmit={handleCreate} id="myform">
            <TextField
              value={staffNumber}
              onChange={(e) => setStaffNumber(e.target.value)}
            />
          </form>
        </DialogContent>
        <DialogActions>
          <Button variant="contained" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          <Button variant="contained" type="submit" form="myform">
            Submit
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

We add the Dialog component to add a dialog box.

Then we add the DialogContent component to add the dialog content pane.

Next, we add the DialogActions component to add the dialog actions pane.

We add the form element in the DialogContent component and we add a Button with type set to submit and the the form attribute set to myForm to let us submit the form when we click on it. This works since the form’s id attribute matches the form attribute of the Button.

Then we set the onSubmit prop of the form to handleCreate to run it when we click on Submit.

In handleCreate, we call e.preventDefault to stop server side submission.

And we call setOpen with false to set open to false.

Since we set the open prop of the Dialog to open, the dialog would close when open is false.

Conclusion

To submit the form that is inside a dialog using React Material UI, we can put a form element inside the dialog and add a input with type submit inside the form.

Categories
React Answers

How to make React Material UI table row and columns sticky?

Sometimes, we want to make React Material UI table row and columns sticky.

In this article, we’ll look at how to make React Material UI table row and columns sticky.

How to make React Material UI table row and columns sticky?

To make React Material UI table row and columns sticky, we can add our own styles to the existing table cell components and return the new component with the styles.

For instance, we write:

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

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    marginTop: theme.spacing(3)
  },
  head: {
    backgroundColor: "#fff",
    minWidth: "50px"
  },
  tableContainer: {
    maxHeight: "400px"
  },
  cell: {
    minWidth: "100px"
  }
}));

const StickyTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white,
    left: 0,
    position: "sticky",
    zIndex: theme.zIndex.appBar + 2
  },
  body: {
    backgroundColor: "#ddd",
    minWidth: "50px",
    left: 0,
    position: "sticky",
    zIndex: theme.zIndex.appBar + 1
  }
}))(TableCell);

const StyledTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white
  },
  body: {
    fontSize: 14
  }
}))(TableCell);

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

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

const data = [
  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)
];

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

  return (
    <div>
      <TableContainer className={classes.tableContainer}>
        <Table stickyHeader>
          <TableHead>
            <TableRow>
              <StickyTableCell className={classes.head}>
                <StyledTableCell className={classes.head} numeric>
                  Dessert (100g serving)
                </StyledTableCell>
                <StyledTableCell className={classes.head} numeric>
                  Calories
                </StyledTableCell>
              </StickyTableCell>
              <StyledTableCell className={classes.head} numeric>
                Calories
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Fat (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Carbs (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {data.map((n) => {
              return (
                <StyledTableRow key={n.id}>
                  <StickyTableCell>
                    <StyledTableCell
                      numeric
                      align="right"
                      className={classes.cell}
                    >
                      {n.name}
                    </StyledTableCell>
                    <StyledTableCell
                      numeric
                      align="right"
                      className={classes.cell}
                    >
                      {n.calories}
                    </StyledTableCell>
                  </StickyTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.fat}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.carbs}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.protein}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.calories}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.fat}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.carbs}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.protein}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.calories}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.fat}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.carbs}
                  </StyledTableCell>
                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.protein}
                  </StyledTableCell>
                </StyledTableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

We call makeStyles with a function that returns some styles for various parts of the table.

Next, we call withStyles with a function with the styles for the cells.

We set the position CSS property to 'sticky' to make the component that we apply the styles to sticky.

Then we call the returned higher order component with TableCell and assign the returned component to StickyTableCell.

Similarly, we call withStyles with TableCell again and TableRow to return styled table cells and table row components.

Next, in App, we call the useStyles hook to return the classes object.

And we apply the styles that we added with makeStyles to various components.

We add the stickyHeader to Table to make the table header row sticky.

And then we use the StickyTableCell we created earlier to add sticky columns.

As a result, we see that the header row of the table and the leftmost 2 columns of the table being sticky.

Conclusion

To make React Material UI table row and columns sticky, we can add our own styles to the existing table cell components and return the new component with the styles.