Skip to content
DeveloperMemos

How to Redirect to Another Page Using React

React, JavaScript1 min read

React is a popular JavaScript library used for building user interfaces. One important feature of any web application is the ability to redirect users from one page to another. In this article, we will discuss two methods of implementing page redirection in React.

Using React Router

React Router is a widely used routing library for React that allows developers to manage different pages in their application. To use React Router for page redirection, you first need to install the package:

1npm install react-router-dom

Once installed, you can import the necessary components and define your routes. Here is an example of how to create a basic router with two routes:

1import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
2
3function App() {
4 return (
5 <Router>
6 <Switch>
7 <Route exact path="/" component={HomePage} />
8 <Route exact path="/about" component={AboutPage} />
9 </Switch>
10 </Router>
11 );
12}
13
14function HomePage() {
15 return <h1>Welcome to the home page!</h1>;
16}
17
18function AboutPage() {
19 return <h1>About us</h1>;
20}

In the above code, we imported BrowserRouter and other components from react-router-dom. We then defined our routes using the Route component.

To redirect the user to another page, you can use history.push() method provided by react-router-dom. Here's an example:

1import { useHistory } from 'react-router-dom';
2
3function LoginPage() {
4 const history = useHistory();
5
6 function handleSubmit(event) {
7 event.preventDefault();
8 // Perform login logic...
9 history.push('/dashboard');
10 }
11
12 return (
13 <form onSubmit={handleSubmit}>
14 <input type="text" placeholder="Email" />
15 <input type="password" placeholder="Password" />
16 <button type="submit">Log in</button>
17 </form>
18 );
19}

In the above code, we used the useHistory() hook to access the history object, which we then used to navigate to the /dashboard page after successful login.

Manually Changing Window Location

If you don't want to use a routing library like React Router, you can also redirect users by manually changing the window location. Here's an example:

1function handleClick() {
2 window.location.href = '/new-page';
3}
4
5function HomePage() {
6 return (
7 <div>
8 <h1>Welcome to the home page!</h1>
9 <button onClick={handleClick}>Go to new page</button>
10 </div>
11 );
12}

In the above code, we defined a function handleClick() that changes the page URL using window.location.href.

Both methods discussed above can be used to implement page redirection in your React application. Choose the method that best suits your needs and build great user experiences!