Skip to main content

Command Palette

Search for a command to run...

Navigating to a different page with Button in React

Published
2 min read
Navigating to a different page with Button in React
C

Hello World! I am Carol Dsilva, A Second Year Information Science Engineering Student at Sir M Visvesvaraya Institute of Technology with a profound interest in Technology and Design.

Navigating between pages in React can seem tricky at first. I searched through lots of guides and examples, but they all talked about using the <a> tag to go to a new page.

<a href='/pagename'>navigation text</a>

You can add this with the help of the react router Dom from app.js. Here is an example of how you can add the router in your project.

import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path='/pagename' element={<PageName/>} />
      </Routes>
    </BrowserRouter>
  );
}

Then, I discovered something cool: with React Router DOM, you can actually use the <button> tag and Navigate to do the same thing! It's like finding a secret shortcut that makes moving around your React app easier.

Here's a step by step on how you can do this.

To begin, ensure you've installed React Router Dom by running the following command in your terminal:

npm i react-router-dom

Next, import the useNavigate Hook into the JavaScript page where you intend to incorporate a button:

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

Then, seamlessly integrate the following code into your export function alongside the button:

export const PageName = () => {
  const navigate = useNavigate(); // Using navigate from useNavigate hook to handle navigation.
  return (
    <button type='submit' onClick={() => navigate('/pagename')}>Button</button>
    // Using onClick event to trigger navigation to the desired page.
    // /pagename should be the url you want to page to navigate to
  );
}

Instead of being limited to the <a> tag, React Router DOM empowers you to leverage buttons for navigation within your application. This approach enables you to craft buttons that seamlessly transport users to various pages within your app.

T
The Murph2y ago

What are the advantages over using an anchor tag?

C

The styling for the < button> tag is more specific and you can add more functionalities to a < button> like submit.

1

More from this blog

C

Carol Dsilva

14 posts

Hello World! I am Carol Dsilva, A Second Year Information Science Engineering Student at Sir M Visvesvaraya Institute of Technology with a profound interest in Technology and Design.