user17161243
user17161243

Reputation:

Redirecting to pages depending on conditionals in ReactJS

Given is an application with 3 pages:

After successful login the user is redirected to a "PrivatPage". On the "PrivatPage" the user has the possibility to return to the "MainPage" or to go to the "UserManagementPage". The part with the redirecting from the "MainPage" to the "PrivatPage" works. The code looks like this:

import PublicPage from "./components/PublicPage";
import PrivatePage from "./components/PrivatePage";
import UserManagementPage from "./components/UserManagementPage";
import React, { useState, Component } from "react";
import { connect } from "react-redux";

const mapStateToProps = state => {
    return state;
};

class App extends Component {
    render() {
        const accessToken = this.props.accessToken;

        console.log(accessToken);
        let workspace;
        if (accessToken) {
            workspace = <PrivatePage />;
        } else {
            workspace = <PublicPage />;
        }

        return <div className="App">{workspace}</div>;
    }
}
export default connect(mapStateToProps)(App);

But how do I use the conditionals to get to the "UserManagementPage" ?

Upvotes: 0

Views: 91

Answers (2)

Bilal Abraham
Bilal Abraham

Reputation: 184

Adding on to private blocks answer you would then in your components use the

<Redirect to='/your-route' />

You would then create a boolean state variable and once it return true you could redirect immediatley like this (where you are rendering jsx):

render() {
    {booleanState && <Redirect to='/your-route' />}
}

Upvotes: 1

timsntech
timsntech

Reputation: 216

if you consider functional components, you could use BrowserRouter as follows with react-router-dom. If you need to handle authentication, you can f.e. build a custom <PrivateRoute /> component and use this on your protected routes instead of <Route />. I always keep these routes in a separate file and import them in App.js. Here for demo purposes routes in App.js:

import { BrowserRouter as Router } from "react-router-dom";
// import your page components
// and add everything else you want to add to your component

const App = () => {

  return (
    <>
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/private" element={<PrivatePage />} />
          <Route path="/public" element={<PublicPage />} />
          <Route path="/user" element={<UserManagementPage />} />
        </Routes>
      </Router>
    </>
  );
};

export default App;

Upvotes: 1

Related Questions