JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Using redirects in React Router

Author:JIYIK Last Updated:2025/03/03 Views:

If you are a developer working on complex web applications, you probably understand the importance of routing. Routing is one of the key parts that make up the navigation system of an application. ReactJs developers tend to use react-router-domthe package to create routes for their applications.
After submitting a form (or any other user action), sometimes the application needs to navigate to a different URL. In this article, we will look at how to handle redirects in React.

Hooks can extend the base functionality of functional components. React developers can use built-in hooks such as useReducer(), useState(), useEffect()or create their own custom versions.

useHistory()Returns a historyinstance containing the component's current location (URL). Handling redirects is not the primary purpose of this hook. However, new versions of React Router (5 and above) allow you to use this hook to redirect users in an efficient and readable way.

Let's look at this example:

import { useHistory } from "react-router-dom"
function SampleComponent() {
  let history = useHistory()
  function handleClick() {
    history.push("/somepage")
  }

  return (
    <span onClick={() => handleClick()}>
      Go home
    </span>
  )
}

In this example, we react-router-domimport useHistorythe hook from the package. We then define a simple functional component that returns a single <span>element with an clickevent handler for the event.

We also create a historyvariable to store useHistory()the instance returned by the hook.

In the body of the event handler function, we use .push()the method and pass a string as a parameter. The parameter of this method will be added to the end of the current URL. So, if our application localhost:3000is running on port , and we have to handle clickthe event, our URL will change to localhost:3000/somepage.

Another way to navigate to a different URL after an action (submitting a form, clicking a button, or any other user action) is to use a custom <Redirect>component. You can "react-router-dom"import it from the library.
You can control when the redirect occurs by conditionally rendering the redirect based on a state value. Let's look at this example:

import React from "react"
import { Redirect } from "react-router-dom"

class MyComponent extends React.Component {
  constructor(props){
     super(props)
     this.state = {
    	    condition: false
  		}
  }
  handleClick () {
    axios.post(/*URL*/)
      .then(() => this.setState({ condition: true }));
  }

  render () {
    const { condition } = this.state;

     if (condition) {
       return <Redirect to='/somePage'/>;
     }
     return <button onClick={() => this.handleClick()}>Redirect</button>;
}

Our state has a conditionproperty which is set to false. Because of this boolean value, <Redirect>the component does not render and the user's URL does not change.

By clicking a single button, the user can trigger an event handler conditionthat sets the property to true. In this case, ifthe condition of the statement will be met and the render function will return <Redirect>a component that takes the user to the specified relative path.

In this case, if our application's homepage is located at localhost:3000, and our <Redirect>component has a property with a value '/somePage'of to, the user will be redirected to the following location: localhost:3000/somePage.

Using useHistory()the hook is not the only way to access the user's current location. Developers can achieve the same functionality in both types of components by reading the property propsof the object .history

If you want a redirect to occur after clicking a button, you must set up a onClickevent handler that uses .push("")the method to provide a relative path to where the user should be redirected. Here is an example:

<button onClick={this.props.history.push('/somePage')}>Redirect to some page </button>

If their current location is localhost:3000on the Home Page, clicking this button will take the user to localhost:3000/somePagethe URL.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Creating a Back Button with React Router

Publish Date:2025/03/10 Views:157 Category:React

To create a back button using React Router: Set the onClick property on the button to a function. Use the useNavigate() hook, e.g. const navigate = useNavigate();. Call the navigate() function, passing it -1 - navigate(-1).

How to remove query parameters using React Router

Publish Date:2025/03/08 Views:176 Category:React

To delete query parameters using React Router: Use the useSearchParams hook to get the search parameters for the current location. Use the delete() method to delete each query parameter, such as searchParams.delete('q'). To update the search parameter

Return to the previous page using React Router

Publish Date:2025/03/08 Views:53 Category:React

To go back to the previous page with React Router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Calls the navigate() function passed to it -1 - navigate(-1) . Calling navigate with -1 is the same as clicking the back button. impo

Programmatically update query parameters in React Router

Publish Date:2025/03/06 Views:73 Category:React

Use the useSearchParams hook to programmatically update query parameters in React Router, for example, setSearchParams({query: myValue}) . The useSearchParams hook is used to read and modify the query string in the URL of the current location. import

React Routing vs React Routing DOM

Publish Date:2025/03/04 Views:175 Category:React

In this article, we will discuss these two React Router libraries and explain the similarities and differences between them.

React Router Authentication

Publish Date:2025/03/04 Views:55 Category:React

This tutorial demonstrates how to set up react-router authentication in React.

History Object in React Router

Publish Date:2025/03/04 Views:130 Category:React

React Router includes a history package, which is similar to the history prop of the window object. In this guide, we will look at the differences between the two.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial