Here are the steps on how to make a navigation bar using React JS:
- Create a new React project. You can do this by using the create-react-app command.
- Create a Navbar component. This component will contain the navigation bar markup and logic.
- Add the Navbar component to your App component. This will make the navigation bar available on all pages of your app.
- Style the Navbar component. You can use CSS to style the navigation bar to match your app’s design.
- Add event handlers to the Navbar component. These event handlers will be triggered when a user clicks on a navigation link.
import React from "react";
const Navbar = () => {
const links = [
{
href: "/",
label: "Home",
},
{
href: "/about",
label: "About",
},
{
href: "/contact",
label: "Contact",
},
];
return (
<nav>
<ul>
{links.map((link) => (
<li key={link.href}>
<a href={link.href}>{link.label}</a>
</li>
))}
</ul>
</nav>
);
};
export default Navbar;
This code creates a simple navigation bar with three links. The links are rendered as <li> elements, and each <li> element contains an <a> element with the link’s href and label. The Navbar component is exported so that it can be used in other components.
To style the navigation bar, you can use CSS. For example, you could add the following CSS to the Navbar component:
nav {
background-color: #fff;
border-bottom: 1px solid #ccc;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: inline-block;
padding: 10px;
}
a {
text-decoration: none;
color: #333;
}
This CSS will style the navigation bar with a white background, a 1px solid bottom border, and some padding. The links will also be styled with black text and no text decoration.
Finally, you can add event handlers to the Navbar component to handle clicks on the navigation links. For example, you could add the following event handlers to the Navbar component:
const Navbar = () => {
const links = [
{
href: "/",
label: "Home",
onClick: () => {
window.location.href = "/";
},
},
{
href: "/about",
label: "About",
onClick: () => {
window.location.href = "/about";
},
},
{
href: "/contact",
label: "Contact",
onClick: () => {
window.location.href = "/contact";
},
},
];
return (
<nav>
<ul>
{links.map((link) => (
<li key={link.href}>
<a href={link.href} onClick={link.onClick}>{link.label}</a>
</li>
))}
</ul>
</nav>
);
};
This code adds an onClick event handler to each link in the links array. The onClick event handler will be triggered when a user clicks on the link, and it will call the window.location.href method to navigate to the link’s href.
This is just a simple example of how to make a navigation bar using React JS. You can customize the navigation bar to match your app’s design and functionality.