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
JavaScript Answers

How to Format a JavaScript Date in YYYY-MM-DD Format?

Extract the Parts of a Date and Put Them Together

One way to format a JavaScript date into the YYYY-MM-DD format is to extract the parts of a date and put them together.

For instance, we can write:

const formatDate = (date) => {
  let d = new Date(date);
  let month = (d.getMonth() + 1).toString();
  let day = d.getDate().toString();
  let year = d.getFullYear();
  if (month.length < 2) {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }
  return [year, month, day].join('-');
}
console.log(formatDate('Febuary 1, 2021'));

We create the formatDate function which takes a date format and return the date string in YYYY-MM-DD format.

We create a Date instance from the date by passing it in.

Then we get the month, day, and year from the d object.

Next, we pad the month and day strings with leading zeroes if their lengths are less than 2 in length.

And finally, we return the year, month, and day joined together with the join method.

Therefore, the console log should log:

'2021-02-01'

We can shorten the function with the padStart method to add the leading zeroes.

To do this, we write:

const formatDate = (date) => {
  let d = new Date(date);
  let month = (d.getMonth() + 1).toString().padStart(2, '0');
  let day = d.getDate().toString().padStart(2, '0');
  let year = d.getFullYear();
  return [year, month, day].join('-');
}
console.log(formatDate('Febuary 1, 2021'));

We call padStart to pad month and day to the length of 2.

And we pad the string with leading zeroes.

And so we should get the same result as the previous example.

Date.protptype.toISOString

Another way to format a JavaScript date to YYYY-MM-DD format is to use the toISOString method.

For instance, we can write:

const formatDate = (date) => {
  const [dateStr] = new Date(date).toISOString().split('T')
  return dateStr
}
console.log(formatDate('Febuary 1, 2021'));

to create the formatDate function and call it.

We create a Date instance from the date parameter.

Then we call toISOString to it to create a date string.

The part before the T is in YYYY-MM-DD format, so we can extract that with split and return it.

Therefore, we should get the same result as the previous examples.

String.prototype.slice

We can use toISOString with the string slice method to extract the substring with the YYYY-MM-DD date string.

For instance, we can write:

const formatDate = (date) => {
  return new Date(date).toISOString().slice(0, 10)
}
console.log(formatDate('Febuary 1, 2021'));

to extract that part of the string.

And we get the same result as before in the console log.

Date.prototype.toLocaleDateString

We can use the toLocaleDateString method to format a date with the Canadian English locale to format a date to YYYY-MM-DD.

For example, we can write:

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('en-CA')
}
console.log(formatDate('Febuary 1, 2021'));

to do this.

We call toLocaleDateString with ‘en-CA’ to format the string with the given locale string.

And we get the same result as before.

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.

Categories
React Answers

How to fix the custom color to Badge component not working with React Material UI?

Sometimes, we want to fix the custom color to Badge component not working with React Material UI.

In this article, we’ll look at how to fix the custom color to Badge component not working with React Material UI.

How to fix the custom color to Badge component not working with React Material UI?

To fix the custom color to Badge component not working with React Material UI, we can use the styled function to create a badge component with custom styling.

For instance, we write:

import React from "react";
import Badge from "@material-ui/core/Badge";
import MailIcon from "@material-ui/icons/Mail";
import { styled } from "@material-ui/core";

const StyledBadge = styled(Badge)({
  "& .MuiBadge-badge": {
    color: "yellow",
    backgroundColor: "green"
  }
});

export default function App() {
  return (
    <StyledBadge badgeContent={130}>
      <MailIcon />
    </StyledBadge>
  );
}

We call styled with Badge to return a function that we call with an object that has the custom badge styles.

We select the badge with the "& .MuiBadge-badge" selector.

And we set the color to 'yellow' and backgroundColor to 'green'.

Finally, we use the StyledBadge component that’s returned by styled with the badgeContent prop to add content into the badge.

And we should see that the badge text is yellow and the badge background is green.

Conclusion

To fix the custom color to Badge component not working with React Material UI, we can use the styled function to create a badge component with custom styling.

Categories
React Answers

How to remove underline from input component with React Material UI?

Sometimes, we want to remove underline from input component with React Material UI.

In this article, we’ll look at how to remove underline from input component with React Material UI.

How to remove underline from input component with React Material UI?

To remove underline from input component with React Material UI, we can set the disableUnderline prop to true.

For instance, we write:

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

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

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <Input
      disableUnderline
      value={age}
      onChange={handleChange}
      placeholder="age"
    />
  );
}

to add the disableUnderline to the Input component.

As a result, we wouldn’t see the underline of the input now.

Conclusion

To remove underline from input component with React Material UI, we can set the disableUnderline prop to true.