Navigating to a different page with Button in React

Navigating to a different page with Button in React

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.