A back button takes the back user to the previous page he visited earlier. An application is a conjugation of various pages; a user can navigate from one page to another page using routes.
In this tutorial, we will learn how to create custom back button with React 18 Router DOM v6. To create a custom back button with React 18 Router DOM v6 we follow these steps
If you already have the React project ready, go on to the next step. Else, run the command for installing a new React project. After the installation process is done, jump into the project’s root:
npx create-react-app react-blog-app
cd react-blog-app
We will be forming two function components, Home and Profile. These components will help us to create routes that will help us go forward and previous in React. Create components/Home.js folder and file, next update with given code:
import React from 'react'
function Home() {
return (
<div>Home page</div>
)
}
export default Home
Create components/Profile.js folder and file, then update with following code:
import React from 'react'
function Profile() {
return (
<div>Profile page</div>
)
}
export default Profile
If you are well versed with node, npm, and command line, installing React Router DOM should be a breeze.
npm install react-router-dom --legacy-peer-deps
If any you want to navigate from www.yourdomain.com/one to www.yourdomain.com by clicking on the back to button.
import Home from "./components/Home";
import Profile from "./components/Profile";
import { Routes, Link, Route, useNavigate } from "react-router-dom";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
const nav = useNavigate();
return (
<div className="container mb-5">
<h2>React Custom Back Button Example</h2>
<div className="list-group mt-4">
<button className="btn btn-primary mb-3" onClick={() => nav(1)}>
Go Onward
</button>
<button className="btn btn-dark" onClick={() => nav(-1)}>
Back to 1 Page
</button>
</div>
<ul className="list-group">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/profile">Profile</Link>
</li>
</ul>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</div>
);
}
export default App;
In order to work Router DOM in React, make sure to add BrowserRouter API in index.js file as suggested below.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
As you can see, we have given a single command below. This will start the server after executing, hence go ahead and run the command and test the functionality.
npm start
http://localhost:3000
This tutorial taught us how to build a dynamic custom back button in React.