How to create Header in React JS ?
Last Updated :
12 Dec, 2023
The Header is an important element of a website’s design. It’s the first impression of the website. It provides useful links to other areas of the website that the user may want to visit. In this article, we will create a functioning Header using React JS and Material UI.
Prerequisites:
Approach:
To create a Header, we will use the App Bar from Material UI which will provide screen titles, navigation, and actions. Also, we will need a ToolBar inside which will set the properties to child components making them all horizontally aligned. Then import the Header component to App.js to render it on the page.
Steps to create React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3:Â After creating the React.js application, install the material-ui modules using the following command.
npm i @material-ui/core @mui/icons-material @mui/material @mui/styled-engine @emotion/react @emotion/styled
Project Structure:
updated project structure
The updated dependencies in package.json file will look like.
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@material-ui/core": "^4.12.4",
"@mui/icons-material": "^5.14.18",
"@mui/material": "^5.14.18",
"@mui/styled-engine": "^5.14.18",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This example uses Material UI AppBar and Toolbar Components to implement a Header in the application.
Javascript
import React from "react" ;
import Header from "./Header" ;
function App() {
return (
<Header />
);
}
export default App;
|
Javascript
import * as React from "react" ;
import AppBar from "@mui/material/AppBar" ;
import Toolbar from "@mui/material/Toolbar" ;
import Typography from "@mui/material/Typography" ;
import Button from "@mui/material/Button" ;
import IconButton from "@mui/material/IconButton" ;
import MenuIcon from "@mui/icons-material/Menu" ;
export default function Header() {
return (
<AppBar position= "static" >
<Toolbar>
{
}
<IconButton
size= "large"
edge= "start"
color= "inherit"
aria-label= "menu"
sx={{ mr: 2 }}
>
{
}
<MenuIcon />
</IconButton>
{
}
<Typography
variant= "h6"
component= "div"
sx={{ flexGrow: 1 }}
>
GeeksforGeeks Header
</Typography>
<Button color= "inherit" >Login</Button>
</Toolbar>
</AppBar>
);
}
|
Step to run the application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...