Categories
React Answers

How to accept only positive unsigned integer values in TextField with React Material-UI?

Sometimes, we want to accept only positive unsigned integer values in TextField with React Material-UI.

In this article, we’ll look at how to accept only positive unsigned integer values in TextField with React Material-UI.

How to accept only positive unsigned integer values in TextField with React Material-UI?

To accept only positive unsigned integer values in TextField with React Material-UI, we can check the value that’s entered into the TextField, then we can change values that aren’t accepted to a valid value.

For instance, we write:

import { TextField } from "material-ui";
import React, { useState } from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";

const min = 1;

export default function App() {
  const [value, setValue] = useState(0);

  return (
    <MuiThemeProvider>
      <div>
        <TextField
          type="number"
          inputProps={{ min }}
          value={value}
          onChange={(e) => {
            if (e.target.value === "") {
              setValue(e.target.value);
              return;
            }
            const value = +e.target.value;
            if (value < min) {
              setValue(min);
            } else {
              setValue(value);
            }
          }}
        />
      </div>
    </MuiThemeProvider>
  );
}

We set the onChange prop to a function that checks the inputted value.

The inputted value is stored in e.target.value.

If it’s less than min, then we set the value state to min with setValue.

Otherwise, we set value to e.target.value.

And we set the value prop to the value state.

Conclusion

To accept only positive unsigned integer values in TextField with React Material-UI, we can check the value that’s entered into the TextField, then we can change values that aren’t accepted to a valid value.

Categories
React Answers

How to wrap or truncate long strings in a React Material-UI ExpansionPanelSummary?

Sometimes, we want to wrap or truncate long strings in a React Material-UI ExpansionPanelSummary.

In this article, we’ll look at how to wrap or truncate long strings in a React Material-UI ExpansionPanelSummary.

How to wrap or truncate long strings in a React Material-UI ExpansionPanelSummary?

To wrap or truncate long strings in a React Material-UI ExpansionPanelSummary, we add the noWrap prop to the Typography component.

For instance, we write:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Accordion from "@material-ui/core/Accordion";
import AccordionSummary from "@material-ui/core/AccordionSummary";
import AccordionDetails from "@material-ui/core/AccordionDetails";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%"
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: theme.typography.fontWeightRegular
  }
}));

const useWidth = () => {
  const [width, setWidth] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const onResize = () => {
      setWidth(window.innerWidth);
    };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return width;
};

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

  return (
    <div>
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography
            noWrap
            className={classes.heading}
            style={{ width: width * 0.8 }}
          >
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget. 1
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography
            noWrap
            className={classes.heading}
            style={{ width: width * 0.8 }}
          >
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget. 2
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
            malesuada lacus ex, sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
    </div>
  );
}

We add the Typography component into the AccordionSummary component.

Then we set the style prop of each Typography component to an object with the width property set to the width we want the text to have.

As a result, we now see that the accordion headings are truncated with the ellipsis at the end.

We defined the useWidth hook to watch for the window’s width and call setWidth to set the width when the window is resized.

We watch the width by calling window.addEventListener with 'resize' and onResize.

And we remove the event listener when we unmount the component by returning a function that calls window.removeEventListener.

And then we return the width and set that as the width property of the object we set as the style prop value.

Conclusion

To wrap or truncate long strings in a React Material-UI ExpansionPanelSummary, we add the noWrap prop to the Typography component.

Categories
React Answers

How to add the outline variant of the date picker with React Material UI?

Sometimes, we want to add the outline variant of the date picker with React Material UI.

In this article, we’ll look at how to add the outline variant of the date picker with React Material UI.

How to add the outline variant of the date picker with React Material UI?

To add the outline variant of the date picker with React Material UI, we set the inputVariant prop of the KeyboardDatePicker to 'outlined'.

For instance, we write:

import * as React from "react";
import "date-fns";
import DateFnsUtils from "@date-io/date-fns";
import {
  MuiPickersUtilsProvider,
  KeyboardDatePicker
} from "@material-ui/pickers";

export default function App() {
  const [date, setDate] = React.useState(new Date());

  return (
    <div>
      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <KeyboardDatePicker
          margin="normal"
          id="date-picker-dialog"
          label="Date picker dialog"
          format="MM/dd/yyyy"
          value={date}
          onChange={(d) => setDate(d)}
          inputVariant="outlined"
        />
      </MuiPickersUtilsProvider>
    </div>
  );
}

First, we wrap MuiPickersUtilsProvider around the KeyboardDatePicker to make the date picker work.

We add a KeyboardDatePicker with the type prop set to 'date' to add a date picker.

Next, we set the inputVariant prop of the KeyboardDatePicker to 'outlined' to make the input show the border.

And we set the value and onChange props to let us get and set the selected date value respectively.

Conclusion

To add the outline variant of the date picker with React Material UI, we set the variant prop of the TextField to 'outlined'.

Categories
React Answers

How to add a close icon in React Material UI Dialog header’s top right corner?

Sometimes, we want to add a close icon in React Material UI Dialog header’s top right corner.

In this article, we’ll look at how to add a close icon in React Material UI Dialog header’s top right corner.

How to add a close icon in React Material UI Dialog header’s top right corner?

To add a close icon in React Material UI Dialog header’s top right corner, we can put the title and the close icon in a Grid component.

For instance, we write:

import * as React from "react";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import IconButton from "@material-ui/core/IconButton";
import CloseIcon from "@material-ui/icons/Close";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";

export default function App() {
  const [open, setOpen] = React.useState();

  return (
    <div>
      <Button onClick={() => setOpen(true)}>Open</Button>
      <Dialog open={open} onClose={() => setOpen(false)}>
        <DialogTitle>
          <Grid container justify="space-between" alignItems="center">
            <Typography variant="div">Dialog</Typography>
            <IconButton onClick={() => setOpen(false)}>
              <CloseIcon />
            </IconButton>
          </Grid>
        </DialogTitle>
        <DialogContent>
          <DialogContentText>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla massa
            felis, dapibus eget posuere ut, lobortis id purus.
          </DialogContentText>
        </DialogContent>
      </Dialog>
    </div>
  );
}

To add the dialog box, we add the Dialog component. We also have a Open Button to open the dialog when we click it.

We set the open state with setOpen to true so that we open the dialog.

And we set the open prop of Dialog to the open state to use the open state to control when the Dialog is opened.

We add the DialogTitle component to add the dialog title. And we add the Grid component inside it to add a flex container that we use to layout the title and close button.

We set the container prop to true to add make the Grid a flex container.

And then we set justify to 'space-between' and alignItems to 'center' to put the title on the top left corner and the close button on the top right corner.

We set the onClick prop of the IconButton to a function that calls setOpen to false to close the dialog.

Also, we set the onClose prop to the same function to close it when we click outside the dialog box.

We add the dialog content in the DialogContentText component.

Conclusion

To add a close icon in React Material UI Dialog header’s top right corner, we can put the title and the close icon in a Grid component.

Categories
React Answers

How to set a value for TextField from Material UI with React?

Sometimes, we want to set a value for TextField from Material UI with React.

In this article, we’ll look at how to set a value for TextField from Material UI with React.

How to set a value for TextField from Material UI with React?

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value.

And we set the onChange prop to a function that sets the state to a the value that’s inputted.

For instance, we write:

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

export default function App() {
  const [value, setValue] = React.useState();

  return (
    <div>
      <TextField value={value} onChange={(e) => setValue(e.target.value)} />
      <Button onClick={() => setValue("")}>Reset Text</Button>
    </div>
  );
}

We call the useState hook to create the value state and the setValue function to set the value state’s value.

Next, we set the value prop of the TextField to the value prop.

And we set the onChange prop of the TextField to a function that calls setValue with e.target.value.

e.target.value has the input value of the TextField.

Next, we add a Button that has the onClick prop set to a function that calls setValue with an empty string to let us clear the input by clicking the button.

Conclusion

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value.

And we set the onChange prop to a function that sets the state to a the value that’s inputted.