Categories
React Answers

How to create a navbar with React Material-UI?

Sometimes, we want to create a navbar with React Material-UI.

In this article, we’ll look at how to create a navbar with React Material-UI.

How to create a navbar with React Material-UI?

To create a navbar with React Material-UI, we can use the AppBar, Tabs, and Tab components.

Then we create our own TabPanel component to add the content for each tab.

For instance, we write:

import * as React from "react";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import TabContext from "@material-ui/lab/TabContext";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper
  }
}));

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div hidden={value !== index} {...other}>
      {value === index && (
        <Box py={3} my={6}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

export default function App() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);
  const handleChange = (_, newValue) => setValue(newValue);

  return (
    <div className={classes.root}>
      <TabContext>
        <AppBar>
          <Tabs value={value} onChange={handleChange}>
            <Tab label="Item 1" />
            <Tab label="Item 2" />
            <Tab label="Item 3" />
            <Tab label="Item 4" />
          </Tabs>
        </AppBar>
        <TabPanel value={value} index={0}>
          Item One
        </TabPanel>
        <TabPanel value={value} index={1}>
          Item Two
        </TabPanel>
        <TabPanel value={value} index={2}>
          Item Three
        </TabPanel>
        <TabPanel value={value} index={3}>
          Item Four
        </TabPanel>
      </TabContext>
    </div>
  );
}

We wrap everything with TabContext so that we can display the right content when we click on each Tab.

We add the AppBar as the container for the Tabs.

And we add the Tab to add the link for each tab.

Next, we set the value prop to value to highlight which tab is clicked.

And we set the onChange prop to handleChange to show set the value state to the index of the tab that’s clicked.

Next, we add the TabPanel component that takes the value and index props.

If value is the same as index, then we show the content of the TabPanel.

The children prop has the contents.

As a result, when we click on each tab, we see the content updated.

Conclusion

To create a navbar with React Material-UI, we can use the AppBar, Tabs, and Tab components.

Then we create our own TabPanel component to add the content for each tab.

Categories
React Answers

How to submit a form by in a React Material UI dialog?

Sometimes, we want to submit a form by in a React Material UI dialog.

In this article, we’ll look at how to submit a form by in a React Material UI dialog.

How to submit a form by in a React Material UI dialog?

To submit a form by in a React Material UI dialog, we set the onSubmit prop to a function that calls e.preventDefault.

For instance, we write:

import * as React from "react";
import Dialog from "@material-ui/core/Dialog";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
import Box from "@material-ui/core/Box";

const useStyles = makeStyles((theme) => ({
  paper: {
    padding: "10px"
  }
}));

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

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <button type="button" onClick={handleOpen}>
        Open Modal
      </button>
      <Dialog open={open}>
        <Box className={classes.paper}>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleClose();
            }}
          >
            <div>
              <TextField name="email" hintText="Email" />
            </div>
            <div>
              <TextField name="pwd" type="password" hintText="Password" />
            </div>
            <div>
              <button type="submit">Submit</button>
            </div>
          </form>
        </Box>
      </Dialog>
    </div>
  );
}

We add a Dialog with the open prop set to open state so that we make sure that the dialog is open only when open is true.

In the Dialog, we add the form element with the TextFields to add the inputs.

Then we add a button with type set to submit to run the function we set as the value of the onSubmit prop.

In the function, we call e.preventDefault to prevent the default server-side submission behavior.

And we call handleClose to set open to false to close the dialog box.

Conclusion

To submit a form by in a React Material UI dialog, we set the onSubmit prop to a function that calls e.preventDefault.

Categories
React Answers

How to disable outside click on a modal with React Material-UI?

Sometimes, we want to disable outside click on a modal with React Material-UI.

In this article, we’ll look at how to disable outside click on a dialog (Modal) with React Material-UI.

How to disable outside click on a dialog modal with React Material-UI?

To disable outside click on a dialog modal with React Material-UI, we can set the onClose prop of the Modal to a function that has the reason as the 2nd parameter.

Then we can check that the reason isn’t 'backdropClick' before we close it.

For instance, we write:

import * as React from "react";
import Modal from "@material-ui/core/Modal";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  paper: {
    position: "absolute",
    backgroundColor: theme.palette.background.paper,
    border: "2px solid #000",
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3)
  }
}));

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

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <button type="button" onClick={handleOpen}>
        Open Modal
      </button>
      <Modal
        open={open}
        onClose={(_, reason) => {
          if (reason !== "backdropClick") {
            handleClose();
          }
        }}
      >
        <div className={classes.paper}>
          <p>hello world</p>
          <button type="button" onClick={handleClose}>
            Close Modal
          </button>
        </div>
      </Modal>
    </div>
  );
}

We call makeStyles with an object with some styles to return the useStyles hook.

Then we add the Modal component into App, which is opened by clicking on the Open Modal button.

The open state is controlled by the open prop.

The handleOpen function sets open to true to open the modal.

And the handleClose function sets open to false to close it.

Next, we add the Modal component to add the modal.

We set the open prop to open to control when it’s opened or closed.

And we set the onClose prop to a function that checks if the reason isn’t 'backdropClick'.

If it isn’t, we call handleClose to close the modal.

In the Modal we add a div with the content.

It has the Close Modal button that has the onClick prop set to handleClose to close the modal when we click it.

As a result, only clicking on the Close Modal button will close the modal.

Conclusion

To disable outside click on a dialog modal with React Material-UI, we can set the onClose prop of the Modal to a function that has the reason as the 2nd parameter.

Then we can check that the reason isn’t 'backdropClick' before we close it.

Categories
React Answers

How to add 2 Papers side by side in a React Material-UI Grid?

Sometimes, we want to add 2 Papers side by side in a React Material-UI Grid.

In this article, we’ll look at how to add 2 Papers side by side in a React Material-UI Grid.

How to add 2 Papers side by side in a React Material-UI Grid?

To add 2 Papers side by side in a React Material-UI Grid, we can add a outer Grid component with the container prop set to make it a container.

Then we can add 2 more Grids inside it to and add one Paper inside each.

For instance, we write:

import * as React from "react";
import { makeStyles } from "@material-ui/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing * 2,
    textAlign: "center",
    color: "green"
  }
}));

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

  return (
    <div className={classes.root}>
      <Grid container spacing={24}>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

We call makeStyles with a function to style add styles for the root and paper classes.

Then we call useStyles in App to return the classes.

Next, we add the Grid with the container prop to make it a container.

Then we add 2 Grids inside to use as containers for the Paper.

We add the item prop to the Grids to make the display correctly as child elements.

They should display side by side if the screen is large and stacked when the screen is small since we set the xs and sm prop column widths.

Finally, we add the Paper in the child Grids to add our content.

Conclusion

To add 2 Papers side by side in a React Material-UI Grid, we can add a outer Grid component with the container prop set to make it a container.

Then we can add 2 more Grids inside it to and add one Paper inside each.

Categories
React Answers

How to set the height and width for responsive chart using React Recharts?

Sometimes, we want to set the height and width for responsive chart using React Recharts.

In this article, we’ll look at how to set the height and width for responsive chart using React Recharts.

How to set the height and width for responsive chart using React Recharts?

To set the height and width for responsive chart using React Recharts, we can wrap our bar chart with the ResponsiveContainer component.

For instance, we write:

import * as React from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from "recharts";

const data = [
  { name: "Page A", uv: 400 },
  { name: "Page A", uv: 300 },
  { name: "Page A", uv: 600 }
];

export default function App() {
  return (
    <ResponsiveContainer width="95%" height={400}>
      <BarChart
        className="barChart"
        width={600}
        height={300}
        data={data}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
        label="heaf"
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="uv" barSize={10} fill="#05386b" />
      </BarChart>
    </ResponsiveContainer>
  );
}

We wrap the BarChart with the ResponsiveContainer to set the BarChart‘s width and height.

And we set the width and height with the width and height props.

We add the BarChart component to render a bar chart.

The data prop has the bar chart data.

The bars are added with the Bar component with the dataKey prop set to the property name of the items in the data array as the value.

To change the bar color, we set the fill prop to the value we want.

We set the margin prop to set the margins of the bar chart.

CartesianGrid adds a grid in the background. XAxis and YAxis adds the x and y axes respectively.

Conclusion

To set the height and width for responsive chart using React Recharts, we can wrap our bar chart with the ResponsiveContainer component.