How to conditionally add routes in React.JS?

I have a Firebase login system and I want to dynamically add routes, if someone enters the correct information, I want her to add the main route and the add route.

var userToken = 'firebase:authUser:AIzaSyDfC9LqfL1rbClhfCOD04BKC9ZIn7UAZ_g:[DEFAULT]';

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Login} />
        <Route path="signup" component={Signup} />
         { localStorage.getItem(userToken) ? (
            <Route path="main" component={Main} />
          ) : (<Redirect from="main" to="/" />)
        }
        { localStorage.getItem(userToken) ? (
            <Route path="add" component={Add} />
          ) : null
        }  
        <Route path="main" component={Main} />
        <Route path="*" component={NotFound} />
    </Router>
    , document.getElementById('container'));

The above code works fine, but it has a drawback, when someone enters the correct information, they have to reload the page and enter the login information again.

Is there a way they don’t need to reload the page after successful authentication?

+4
source share
2 answers

SecureMain SecureAdd , . , NotFound . ( , , ):

import React from 'react';
import Main from './Main';
import NotFound from './NotFound';

export default class SecureMain extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = { token: localStorage.getItem(userToken) };
  }
  render() {
    if (this.state.token) return <Main {...this.props} />;
    else return <NotFound {...this.props} />;
  }
}

.

, @ZekeDroid " ":

client-side security IRL

+8

. . , Redux , Router . , , , onChange, , localStorage. ( Router), , Routes!

: - , , { true ? <Route path="add" component={Add} /> : null }, , .

+3

Source: https://habr.com/ru/post/1662858/


All Articles