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:155 Category:React

使用 React Router 创建后退按钮: 将按钮上的 onClick 属性设置为函数。使用 useNavigate() 钩子,例如 const navigate = useNavigate();。调用 navigate() 函数,传递它 -1 - navigate(-1)。

How to remove query parameters using React Router

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

使用 React 路由器删除查询参数:使用 useSearchParams挂钩获取当前位置的搜索参数。使用 delete() 方法删除每个查询参数,例如 searchParams.delete('q')。更新搜索参数,例如 setSearchParams(searchP

Return to the previous page using React Router

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

使用 React Router 返回上一页: 使用 useNavigate() 钩子,例如 const navigate = useNavigate(); . 调用传递给它的 navigate() 函数 -1 - navigate(-1) 。 使用 -1 调用 navigate 与点击后退按钮相同。 import { Li

Programmatically update query parameters in React Router

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

使用 useSearchParams 钩子以编程方式更新 React 路由器中的查询参数,例如 setSearchParams({query: myValue}) 。 useSearchParams 钩子用于读取和修改当前位置的 URL 中的查询字符串。 import React from re

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:54 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