To create a navigation bar in React, you can use the react-router-dom library to handle routing and the nav element to create the navigation bar itself. Here is an example of a simple navigation bar that has three routes:
import { NavLink, Route } from 'react-router-dom';
function Navigation() {
return (
<nav>
<ul>
<li>
<NavLink to="/">Home</NavLink>
</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
<li>
<NavLink to="/contact">Contact</NavLink>
</li>
</ul>
</nav>
);
}
function App() {
return (
<div>
<Navigation />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
);
}
In this example, we are using the NavLink component from react-router-dom to create the individual links in the navigation bar. The to prop of the NavLink component specifies the route that the link should navigate to when clicked. The Route component from react-router-dom is used to define the different routes in the application, and the component prop specifies the component that should be rendered when the route is active.
You can also style the navigation bar using CSS. For example, you could add a class to the nav element and then define styles for that class in a stylesheet.
.nav {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #333;
color: #fff;
padding: 0.5rem 1rem;
}
.nav ul {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.nav li {
margin: 0 0.5rem;
}
.nav a {
color: #fff;
text-decoration: none;
}
.nav a:hover {
color: #ccc;
}
This will create a navigation bar with a dark background, white text, and links that change color when hovered over. You can customize the styles to suit your needs.
