Table of Contents
In this article, we will see how to redirect to another page in React. We will also learn how to redirect to an external URL in React.
Project Setup
Create react app using the following command.
1npx create-react-app react-redirect
Now install react-router-dom:
1npm install react-router-dom
Create 2 components Home
and About
in the src
folder.
1import React from "react"23const Home = () => {4 return <div>Home</div>5}67export default Home
1import React from "react"23const About = () => {4 return <div>About</div>5}67export default About
Adding routes
Now add the routes in the App.js
file.
1import { BrowserRouter, Route, Routes } from "react-router-dom"2import "./App.css"3import Home from "./Home"4import About from "./About"56function App() {7 return (8 <BrowserRouter>9 <div className="App">10 <Routes>11 <Route path="/" element={<Home />} />12 <Route path="/about" element={<About />} />13 </Routes>14 </div>15 </BrowserRouter>16 )17}1819export default App
Now if you run the app and access http://localhost:3000/ you will see the Home page and if you access http://localhost:3000/about you will see the About page.
Redirecting from the home page to the about page
Now use the Link component from react-router-dom to redirect from the home page to the about page.
1import { BrowserRouter, Route, Routes, Link } from "react-router-dom"2import "./App.css"3import Home from "./Home"4import About from "./About"56function App() {7 return (8 <BrowserRouter>9 <div className="App">10 <ul>11 <li>12 <Link to="/">Home</Link>13 </li>14 <li>15 <Link to="/about">About</Link>16 </li>17 </ul>1819 <Routes>20 <Route path="/" element={<Home />} />21 <Route path="/about" element={<About />} />22 </Routes>23 </div>24 </BrowserRouter>25 )26}2728export default App
Redirecting to an external URL
If you want to redirect to an external URL, you can use the window.location.href
property.
1import { BrowserRouter, Route, Routes, Link } from "react-router-dom"2import "./App.css"3import Home from "./Home"4import About from "./About"56function App() {7 return (8 <BrowserRouter>9 <div className="App">10 <ul>11 <li>12 <Link to="/">Home</Link>13 </li>14 <li>15 <Link to="/about">About</Link>16 </li>17 <li>18 <button19 onClick={() => {20 window.location.href = "https://example.com"21 }}22 >23 Example.com24 </button>25 </li>26 </ul>2728 <Routes>29 <Route path="/" element={<Home />} />30 <Route path="/about" element={<About />} />31 </Routes>32 </div>33 </BrowserRouter>34 )35}3637export default App
To open in a new tab, you can update the function as follows:
1<button2 onClick={() => {3 window.open("https://example.com", "_blank")4 }}5>6 Example.com7</button>
Do follow me on twitter where I post developer insights more often!