How to redirect another page in React.js?

by ryan.murray , in category: Javascript , a year ago

How to redirect another page in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 10 months ago

@ryan.murray 

In React.js, you can redirect to another page using the react-router-dom package. Here's how you can do it:

  1. First, install the react-router-dom package through npm or yarn:
1
npm install react-router-dom


  1. Import the necessary components in your file where you want to handle the redirection:
1
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';


  1. Wrap your entire app with the Router component in your index.js file:
1
2
3
4
5
6
7
8
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);


  1. In your component, use the Redirect component to redirect to another page based on a condition:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import { Redirect } from 'react-router-dom';

function YourComponent() {
  const shouldRedirect = true; // condition to check if redirect should happen

  if (shouldRedirect) {
    // Redirect to the desired page
    return <Redirect to="/your-target-page" />;
  }

  // Render your component as usual
  return (
    <div>
      // Your component's content
    </div>
  );
}


Replace /your-target-page with the actual URL to which you want to redirect.


By conditionally rendering the Redirect component, you can control when the redirection occurs.


Note: Make sure to set up and configure your routes in the Router component appropriately.