A
A
Apl-by2021-02-07 15:09:42
React
Apl-by, 2021-02-07 15:09:42

What changes in React logic when using a HOC component in routing?

Hello. I'm trying to understand the logic. There is a simplified code:

import React from 'react';
import './App.css';
import { Switch, Route, Redirect, BrowserRouter } from "react-router-dom";

function ProtectedRoute({ component: Component, ...props }) {
  return (
    <Route exact path={props.path}>
      <Redirect to="/sign-in" />
    </Route>)
}

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <Switch>
      **Вариант 1:**  <ProtectedRoute path="/" />
    
      **Вариант 2:**  <Route exact path="/">
                         <Redirect to="sign-in" />
                      </Route> 
   
          <Route path="/sign-in">
            <div>Login</div>
          </Route>
          <Route path="/sign-up">
            <div>Register</div>
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
    
}

export default App;

With option 1, it won't redirect anything, even though the component returns the same Route as in option 2. What's the difference between options 1 and 2?

And the second question. If you do not use Switch, and in HOC ProtectedRoute instead

return (
    <Route exact path={props.path}>
      <Redirect to="/sign-in" />
    </Route>)

use
return (
    <Route exact path={props.path}>
      {() => <Redirect to="/sign-in" />}
    </Route>)

then no matter what address we specify, we will always be redirected to /sign-in. Although Route seems to have exact for path="/". What is the difference for react between
<Redirect to="/sign-in" /> и () => <Redirect to="/sign-in" />
in this case?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question