Home >Web Front-end >JS Tutorial >How to Programmatically Navigate in React Router?
Programmatically Navigate using React-Router
Problem:
In a React application, you need to programmatically change the route based on a condition (e.g., checking if a user is logged in). However, you cannot modify state directly within the render function.
Solution:
To achieve this, there are several strategies that can be employed, depending on the version of React-Router being utilized:
React-Router v4:
React-Router v2 or v3:
Implementation:
Using withRouter (React-Router v4):
import { withRouter } from 'react-router'; class App extends React.Component { componentDidMount() { // Check if the user is logged in if (isLoggedIn) { // Navigate to the home page using history.push this.props.history.push('/home'); } } render() { // Display the login component if the user is not logged in return <Login />; } } export default withRouter(App);
Using Redirect (React-Router v4):
class App extends React.Component { render() { if (isLoggedIn) { // Redirect to the home page using <Redirect> return <Redirect to="/home" />; } // Display the login component if the user is not logged in return <Login />; } }
The above is the detailed content of How to Programmatically Navigate in React Router?. For more information, please follow other related articles on the PHP Chinese website!