How to use the Link Component In ReactJS

In this approach we are using the Link component from react-router-dom that allows us to create links that navigate to different routes within React application. The Link component renders an anchor (<a>) tag with an href attribute set to the specified route.

Syntax:

<Link to="path-name">

Example: Below is the implementation for above approach.

JavaScript
// App.js
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom'
import MyComponent from './components/MyComponent';
import Profile from './components/Profile';

const App = () => {

    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MyComponent />} />
                <Route path="/profile" element={<Profile />} />
            </Routes>
        </BrowserRouter>
    );
};

export default App;
JavaScript
// components/MyComponent.js
import React from 'react';
import { Link } from 'react-router-dom';

function MyComponent() {
    return (
        <div>
            <h1>Welcome to w3wiki</h1>
            <h3>Navigate using Link component</h3>
            <Link to="/profile">
                <button>Go to profile</button>
            </Link>
        </div>
    );
}
export default MyComponent;
JavaScript
// components/Profile.js

import React from 'react';

const Profile = () => {
    return (
        <>
            <h1>Welcome to Your Profile</h1>
            <p>This is your profile page.
                You can view and edit your profile information here.
            </p>
        </>
    );
};

export default Profile;

Output:



How to programmatically navigate using React Router ?

React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience.

We will discuss the different approaches to navigating using React Router:

Table of Content

  • Using the useNavigate hook
  • Using the Link Component

Similar Reads

Using the useNavigate hook

In this approach, we are using the useNavigate hook to programmatically navigate. This hook provides a navigation function that allows us to navigate to a different route within the application....

Using the Link Component

In this approach we are using the Link component from react-router-dom that allows us to create links that navigate to different routes within React application. The Link component renders an anchor () tag with an href attribute set to the specified route....