How to redirect to another page in react js step by step
Redirecting to another page in a React application can be done using the ‘react-router-dom’ library. Here’s a step-by-step guide on how to achieve this:
Step 1: Set Up Your React Project
If you haven’t created a React project yet, you can use Create React App:
npx create-react-app my-react-app cd my-react-app
Step 2: Install react-router-dom
Install the ‘react-router-dom’ library:
npm install react-router-dom
Step 3: Create Components and Routes
Create the components for your pages. For example, you might have a ‘Home’ component and an ‘About’ component. Then, set up your routes using react-router-dom. Create a file named ‘App.js’:
// src/App.js import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Home from './components/Home'; import About from './components/About'; function App() { return (); } export default App;
Step 4: Create Home and About Components
Create the ‘Home.js’ and ‘About.js’ components:
Home.js
// src/components/Home.js import React from 'react'; const Home = () => { return (); }; export default Home;Home
Welcome to the Home page!
About.js
// src/components/About.js import React from 'react'; const About = () => { return (); }; export default About;About
This is the About page.
Step 5: Redirect to Another Page
Now, let’s add a button in the ‘Home’ component that redirects to the ‘About’ page when clicked. Update the ‘Home.js’ file:
// src/components/Home.js import React from 'react'; import { useHistory } from 'react-router-dom'; const Home = () => { const history = useHistory(); const redirectToAbout = () => { history.push('/about'); }; return (); }; export default Home;Home
Welcome to the Home page!
In this example, the ‘useHistory’ hook from ‘react-router-dom’ is used to get access to the ‘history’ object. The ‘redirectToAbout’ function uses `history.push(‘/about’)` to navigate to the ‘About’ page when the button is clicked.
Step 6: Run Your React App
Save your files and run:
npm start
Visit ‘http://localhost:3000’ in your browser, and you should see the Home page. Clicking the “Go to About” button should redirect you to the About page.
Adjust component names and paths based on your specific project structure.