0
0
ReactHow-ToBeginner · 3 min read

How to Use Link Component in React for Navigation

Use the Link component from react-router-dom to create navigation links that change the URL and render components without reloading the page. Wrap the text or elements inside <Link to="/path"></Link> to specify the target route.
📐

Syntax

The Link component is imported from react-router-dom. Use it like an anchor tag but with a to prop instead of href. The to prop defines the path to navigate to.

  • to: The URL path to navigate.
  • Children: The clickable content inside the link.
jsx
import { Link } from 'react-router-dom';

function Navigation() {
  return <Link to="/target-path">Link Text</Link>;
}
💻

Example

This example shows a simple React app with two pages and navigation links using Link. Clicking the links changes the page content without reloading.

jsx
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 Page</h2>;
}

export default function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}
Output
The app shows a navigation bar with 'Home' and 'About' links. Clicking 'Home' displays 'Home Page'. Clicking 'About' displays 'About Page'. Navigation happens without page reload.
⚠️

Common Pitfalls

  • Using <a> tags instead of Link causes full page reloads.
  • Forgetting to wrap your app in <BrowserRouter> or <Router> causes Link to not work.
  • Using href instead of to prop on Link is incorrect.
jsx
/* Wrong: causes full page reload */
<a href="/about">About</a>

/* Right: client-side navigation */
<Link to="/about">About</Link>
📊

Quick Reference

PropDescription
toString or object path to navigate to
replaceBoolean to replace history instead of pushing (optional)
stateObject to pass location state (optional)
childrenContent inside the link (text or elements)

Key Takeaways

Always import Link from react-router-dom to create navigation links.
Use the to prop to specify the target route path.
Wrap your app in BrowserRouter or Router for Link to work.
Avoid using anchor tags for navigation to prevent full page reloads.
Link enables smooth client-side navigation in React apps.