1

my app component redirects a used based if they are logged in = true, I used an online example after trying various methods, if there is a more simple functional react way to do it, please show me,

If user is Logged in , I want them to go to /createpost else I want them to go to the /login route, I want to protect the /createpost route that user has to be logged in, but that is a task for another time, though ideas appreciated..

sandbox: https://codesandbox.io/s/focused-sammet-eitqr

my app component

const App = () => {
  return (
    <Router>
      <Switch>
        <Route component={Navbar} />
        <Route exact path="/Home" component={Home} />
        <Route exact path="/posts" component={ViewPost} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />

        <PrivateRoute
          path="/createpost"
          component={CreatePost}
          isAuthenticated={false}
        />
      </Switch>
    </Router>
  );
};

PrivateRoute component

export const PrivateRoute = ({
  component: Component,
  isAuthenticated,
  ...rest
}) => (
  <Route
    {...rest}
    render={props =>
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

  • In order to import a component name without `{ }`s around it, you should export it as `default`, Your codesandbox throws an error about that. See maybe this: https://stackoverflow.com/q/31852933/4636715 – vahdet Dec 26 '19 at 13:01
  • sorry fixed that, missed it first time. –  Dec 26 '19 at 13:05
  • 1
    take a look at [this](https://stackblitz.com/edit/react-djsizj?file=index.js) demo – Yousaf Dec 26 '19 at 13:48
  • really cool actually, thanks –  Dec 26 '19 at 14:01

1 Answers1

0

I did it by below code -

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import { baseURL } from './components/action';
import './App.css';
import TopNavBar from './components/TopNavBar';
import SideNavBar from './components/sideNavBar';
import Footer from './components/footer';
import DashBoard from './components/dashBoard';
import Media from './components/media';
import Login from './components/Login';
import Registration from './components/Registration';
import ChangePassword from './components/changePassword';
import ForgotPassword from './components/forgotPassword';
import MyProfile from './components/myProfile';
import PageNotFound from './components/pageNotFound';

class App extends Component {
  render() {
    if (
      localStorage.getItem('token') !== undefined &&
      localStorage.getItem('token') !== '' &&
      localStorage.getItem('token') !== null
    ) {
      var token = localStorage.getItem('token');
    }

    const defaultparams = { params: { p1: '', p2: '' } };

    return (
      <BrowserRouter basename={baseURL}>
        <div>
          {token ? <TopNavBar /> : ''}
          {token ? <SideNavBar /> : ''}
          <div className="page_content">
            <Switch>
              <Route
                path="/"
                exact
                render={() => {
                  return token ? (
                    <DashBoard />
                  ) : (
                    <Login match={defaultparams} />
                  );
                }}
              />
              <Route
                path="/dashboard"
                render={() => {
                  return token ? <DashBoard /> : <Redirect to="/login" />;
                }}
              />
              <Route
                path="/media"
                render={() => {
                  return token ? <Media /> : <Redirect to="/login" />;
                }}
              />
              <Route path="/login/:p1?/:p2?" component={Login} />
              <Route
                path="/signup"
                render={() => {
                  return token ? (
                    <Redirect to="/dashboard" />
                  ) : (
                    <Registration />
                  );
                }}
              />
              <Route
                path="/forgotpassword"
                render={() => {
                  return token ? (
                    <Redirect to="/dashboard" />
                  ) : (
                    <ForgotPassword />
                  );
                }}
              />
              <Route
                path="/changepassword"
                render={() => {
                  return token ? <ChangePassword /> : <Redirect to="/login" />;
                }}
              />
              <Route
                path="/myprofile"
                render={() => {
                  return token ? <MyProfile /> : <Redirect to="/login" />;
                }}
              />
              <Route path="" component={PageNotFound} />
            </Switch>
          </div>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

You need to check token. If exists then load the component otherwise redirect the user.

Alok Mali
  • 2,821
  • 2
  • 16
  • 32
  • so no need to make a component to handle the logic we can just do it on the root app.js page in the browser router? –  Dec 26 '19 at 13:10
  • can you explain this ? I'm confused about the purpose of match and default params –  Dec 26 '19 at 13:14