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.
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.
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;
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.
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.