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.