Navigate on Path by Button Click in React Router



React applications often require a convenient method for navigating different routes based on a user's action like clicking a button. However, the biggest hurdle in executing such a task is efficiently executing navigation without reloading the entire page or breaking the single-page application (SPA) experience. This post shows how to efficiently navigate a path by clicking a button in react-router.

Prerequisite

You are required to have a React development environment by installing Node.js and your preferred code editor. Apart from that, you are also required to install react-router-dom using npm or yarn.

Install react-router-dom Module
npm install react-router-dom

Project Structure

There is no need to create any file or directory we will work on the default project structure.


Approach

The stages below illustrate the basics of creating functional navigation on a path by button by clicking on a button in a React application.

Step 1: Installing the Routing Functionality

The first step in your approach is to install the react-router-dom package in your terminal to access the React routing functionality. You must wrap your app in a <BrowserRouter> and <Router> to ensure you have enabled the routing across your application.

Step 2: Define Routes

In this section, your task will involve the utilization of the Routes and Route components from the installed react-router-dom package to define the different paths in your react application. To ensure everything works seamlessly, you should to ensure each path maps to a corresponding component to render when that route is accessed.

Step 3: Initiate the useNavigate Hook

Locate the component where you want the button click to trigger navigation before you can import and utilize the useNavigate hook. Your next step in this section is to call the navigate('/desired-path') within the buttons onClick event and help you navigate to the specified folder.

Step 4: Insert InLine CSS

Inserting the InLine CSS styling is recommended if you want to spruce up the appearance of your react application. The InLine CSS styling method doesn't require the installation of extra packages. However, you can also install CSS-in-JS libraries like the Styled Components if you want to access more styling functionalities.

Example

Here we have created a home page that navigates to the About page, you can create different files for that but here we worked on a single file to keep it simple.

// File name - App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes, useNavigate } from 'react-router-dom';

function Home() {
  const navigate = useNavigate();

  const handleNavigation = () => {
    navigate('/about');
  };

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1 style={{ color: '#333', fontFamily: 'Arial' }}>Home Page</h1>
      <button
        style={{
          backgroundColor: '#4CAF50',
          color: 'white',
          border: 'none',
          padding: '10px 20px',
          textAlign: 'center',
          textDecoration: 'none',
          display: 'inline-block',
          fontSize: '16px',
          margin: '10px 2px',
          cursor: 'pointer',
          borderRadius: '5px',
        }}
        onClick={handleNavigation}
      >
        Go to About Page
      </button>
    </div>
  );
}

function About() {
  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1 style={{ color: '#333', fontFamily: 'Arial' }}>About Page</h1>
    </div>
  );
}

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

export default App;

Output

Here you can check that we can navigate to the About Us page through a button click.


Conclusion

In the above article, we have covered how to install the react-router-dom package to access the routing functionality in React. We have also covered how you can use the react-router-dom package to create a Homepage and a navigation button that redirects you to an About page. The example above is meant to give you a basic understanding of how React works. However, you can also experiment with the navigation functionality using multiple pages to get a better grasp of the technique.

Nickey Bricks
Nickey Bricks

Technical Writer

Updated on: 2024-09-12T13:27:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements