0
0
Reactframework~5 mins

Navigation links in React

Choose your learning style9 modes available
Introduction

Navigation links help users move between different parts of a website or app easily.

When you want to let users jump to different pages or sections.
When building a menu or sidebar for your app.
When creating buttons or links that change the view without reloading the page.
When you want to highlight the current page the user is on.
Syntax
React
import { Link } from 'react-router-dom';

<Link to="/about">About Us</Link>

Use Link from react-router-dom to create navigation links without full page reloads.

The to attribute sets the path to navigate to.

Examples
A simple link to the home page.
React
import { Link } from 'react-router-dom';

<Link to="/home">Home</Link>
Link with an ARIA label for better accessibility.
React
<Link to="/profile" aria-label="Go to your profile">Profile</Link>
Link with CSS classes to style the active navigation item.
React
<Link to="/settings" className="nav-link active">Settings</Link>
Sample Program

This React app uses react-router-dom to create navigation links. Clicking 'Home' or 'About' changes the displayed page without reloading the browser. The navigation is keyboard accessible and uses semantic HTML.

React
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function About() {
  return <h2>About Us</h2>;
}

function App() {
  return (
    <Router>
      <nav aria-label="Main navigation">
        <ul style={{ display: 'flex', gap: '1rem', listStyle: 'none' }}>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>
      <main>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </main>
    </Router>
  );
}

export default App;
OutputSuccess
Important Notes

Always use semantic HTML elements like <nav> and <ul> for navigation lists.

Use ARIA labels to improve accessibility for screen readers.

React Router's Link prevents full page reloads, making navigation faster and smoother.

Summary

Navigation links let users move between pages or sections easily.

Use Link from react-router-dom for smooth client-side navigation.

Make navigation accessible with semantic HTML and ARIA labels.