How to Redirect to Another Page in ReactJS

  • react-js
  • 87 Views
  • 4 Min Read
  • 6 May 2024

Hi developer! Redirecting users to different pages within a React JS application is a common requirement on websites, and it's made easy with the react-router-dom package. This allows seamless navigation between various pages without reloading the full page.

 

In this guide, we'll walk through the process of redirecting to another page in a React JS application step by step, with complete and clear explanations with code examples.

 

So let's get started. 

 

 

Step 1: Set Up Your React Application

 

Before initiating the project setup, ensure that Node.js and npm are installed on your system. If you don't have them installed yet, you can download and install them from the official Node.js website.

 

Now, create a new React application using the Create React App. Open your terminal and execute the following commands:

 
npx create-react-app my-app

cd my-app
 

This command will create a new React application named "my-app" and initialize the development server.

 

 

Step 2: Installing Dependencies

 

To make it so users can move around your website in React, you need to create navigation parts and set up paths using React Router.

 

Navigate to your project directory and install React Router by running the following command:

 
npm i react-router-dom
 

Ensure that the React Router is installed correctly by checking the dependencies section in your package.json file.

 

React Router

 

 

Step 3: Modularizing Your Components

 

One important concept in React is building your app using components. Organizing your code into modular components enhances reusability and maintainability. Let's first create a components folder within the src directory of your project. Within this components directory, we'll create separate files for each component:

 

  • Home.jsx: Renders the home page.
  • About.jsx: Renders the about page.
  • Contact.jsx: Renders the contact page.
  • PageNotFound.jsx: Renders a 404 error page.
  • NavLinks.jsx: Renders navigation links.

 

React Router Folder Structure
 
 

Step 4: Simplifying Development by Creating Separate Component Files

 

Include this code in your Home.jsx file.

 
// components/Home.jsx
import React from "react";

function Home() {
    return (
        <div className="container">
            <h1>Home Page</h1>
        </div>
    );
}

export default Home;

 

This code makes a part of the home page in React. It displays the title 'Home Page'.

 

Include this code in your About.jsx file.

 
// components/About.jsx
import React from "react";

function About() {
    return (
        <div className="container">
            <h1>About Page</h1>
        </div>
    );
}

export default About;

 

This code makes a component of the About page in React. It displays the title 'About Page'.

 

Include this code in your Contact.jsx file.

 
// components/Contact.jsx
import React from 'react';

function Contact() {
    return (
        <div className='container'>
            <h1>Contact-us Page</h1>
        </div>
    )
}

export default Contact;

 

This code creates a component called Contact in React. It shows the heading "Contact-us Page".

 

Include this code in your PageNotFound.jsx file.

 
// components/PageNotFound.jsx
import React from 'react';

const PageNotFound = () => {
    return (
        <div className='container'>
            <h1>404 - Page Not Found</h1>
        </div>
    );
}

export default PageNotFound;

 

This code makes a component for the PageNotFound page in React. It shows the title '404 - Page Not Found'. This component is handy: it pops up when users manually write incorrect URLs or try to access non-existent pages, providing a clear and informative error message to direct them properly.

 

Include this code in your NavLinks.jsx file.

 
// components/NavLinks.js
import React from "react";
import { Link } from "react-router-dom";

function NavLinks() {
    return (
        <div style={{ display: "flex", justifyContent: "end", marginRight: "50px", gap: "20px" }} >
            <Link style={{ textDecoration: 'none' }} to="/">Home</Link>
            <Link style={{ textDecoration: 'none' }} to="/about">About</Link>
            <Link style={{ textDecoration: 'none' }} to="/contact-us">Contact Us</Link>
        </div >
    );
}

export default NavLinks;

 

This file is designed to set up navigation links using React Router. People can click on these links to go to different pages of your site.
 
The to="/": This link directs users to the homepage, following the common convention of using "/" for straightforward access to the main (Home) page.
 
The to="/about": This link guides users to the about page.
 

The to="/contact-us": This link guides users to the contact page.

 

 

Step 5: Integrating Components into Your Application

 

In your App.js file, import and utilize the NavLinks component to render navigation links:

 

// App.js
import React from "react";
import NavLinks from "./components/NavLinks";

function App() {
    return (
        <div >
            <NavLinks />
        </div>
    );
}

export default App;

 

Additionally, integrate React Router into your application by defining routes in the index.js file:

 
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from './components/Contact';
import PageNotFound from './components/PageNotFound';
import App from './App';
import './App.css'

ReactDOM.createRoot(document.getElementById("root")).render(
    <>
        <Router>
            <App />
            <Routes>
                <Route exact path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                <Route path="/contact-us" element={<Contact />} />
                <Route path='*' element={<PageNotFound />} />
            </Routes>
        </Router >
    </>
);
 

The index.js file in a React application is important because it helps manage how users move around the website.

 

Setting Up Paths: This file provides paths for different parts of the website. When users visit specific URLs like "/",  "/about" or "/contact-us", it directs them to the corresponding sections of the site.

 

Dealing with Mistakes: Sometimes users may enter incorrect URLs or try to access pages that don't exist. The index.js file handles this gracefully by including a route with * as the path. This universal (*) route ensures that any unrecognized URL displays a helpful message, such as "Oops! Page not found".

 

 

Step 6: Enhancing Your Application with Styling (Optional)

 

You may consider the following code for your App.css file if desired:

 
/* App.css */
body {
    font-family: cursive;
}

.container {
    height: 100vh;
    display: grid;
    place-items: center;
}
 

You can make this project even more stylish with the help of CSS or Tailwind. Kindly keep in mind, in this project, we've mainly concentrated on making things work rather than making them look fancy.

 

 

Step 5: Run and test your project 

 

Start your project by running the "npm start" command in your terminal.

 

React Router Dom

 

Congratulations! We are sure that with these simple steps, you have successfully created your project to redirect to another page in React JS.

 

 

Conclusion

 

You can further enhance this project by adding a login button for the user to access the dashboard. Also, feel free to get creative with your website's design. You can switch up the heading tag and add more design elements or content on the Home, About, and Contact pages—whether it's images, buttons, text, animations, or whatever else inspires you. With a bit of imagination, you can create an awesome website once you've understood the concepts explained in this article!

 

If you have any questions about this article or any other web development, you can ask them in the question box given below, and you will get the answer soon.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....