Using the Link Component in React Router

Using the Link Component in React Router

Building a Job Board Application with React Router 

                   Welcome back to our tutorial series on building a Job Board application using React Router! In this blog post, we’ll dive into using the Link component for navigation and address styling concerns to enhance the navigation experience in our application.

 Using the Link Component for Navigation

Introduction to the Link Component

The Link component in react-router-dom is used to create navigational links in your application. Unlike traditional anchor tags (<a>), the Link component prevents the page from reloading and allows for smooth navigation within the single-page application.

Setting Up Navigation Links

Let’s create a navigation bar with links to our Home and About pages using the Link component.

  1. Create a Navigation Component:

				
					import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </nav>
  );
}
export default Navigation;

				
			

2.Add Navigation to App Component: Import the Navigation component and include it in your App component.

				
					import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Navigation from './Navigation';

function App() {
  return (
    <Router>
      <div className="App">
        <Navigation />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>
    </Router>
  );
}
export default App;

				
			

Styling the Navigation Component

To enhance the look and feel of our navigation bar, let’s add some basic styles. Create a CSS file, e.g., Navigation.css, and import it into the Navigation component.

  1. Create Navigation.css:

				
					nav {
  background-color: #333;
  padding: 1rem;
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
}

nav ul li {
  margin-right: 1rem;
}

nav ul li a {
  color: white;
  text-decoration: none;
}

nav ul li a:hover {
  text-decoration: underline;
}

				
			

2.Import CSS in Navigation Component:

				
					import './Navigation.css';

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </nav>
  );
}
export default Navigation;

				
			

        To recap, we introduced the Link component for creating navigational links in our application. We also addressed styling concerns by adding a basic CSS file to enhance the navigation bar’s appearance.

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *

Enquire Now