Reputation: 2685
I am new to the react js. I have gone through lots of the tutorials for using the react router. So, the way I am using is like this
**index.js**
ReactDOM.render(<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
App.js
const store = configureStore()
class App extends React.Component {
render() {
return (
<Provider store={store}>
<div>
<Main />
</div>
</Provider>
)
}
Main.js
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import PrivateRoute from '../../privateRoute/component/PrivateRoute';
const LandingScreen = () => {
return (
<div>LandingScreen is theere</div>
)
}
const LoginComponent = () => {
return (
<div>LoginComponent</div>
)
}
export default class Main extends Component {
render() {
return (
<Router history={history}>
<Switch>
<PrivateRoute exact path="/" component={LandingScreen} />
<Route exact path="/login" component={LoginComponent} />
</Switch>
</Router>
)
}
}
In privateRoute.js
const PrivateRoute = ({ component: Component, isFetching, hasUserLogIn, path, ...rest }) => {
return localStorage.getItem("access_token") ?
(
<Route
{...rest}
path={path}
component={Component}
/>
)
:
(
<Redirect
to={{
pathname: "/login",
state: { from: path }
}}
/>
)
};
So this way I have added the routes in my project. So, I am confused weather I am using it in the right way or not. Can any one suggest me or help me with this ?
Upvotes: 0
Views: 59
Reputation: 15688
Regarding your localStorage issue. Try setting up your PrivateRoute like this
const PrivateRoute = ({ component: Component, auth, ...rest}) => {
return(
<Route
{...rest}
//route has a render prop that lets you create a component in-line with the route
render = {props =>
localStorage.getItem("access_token") ? (
<Component {...props} />
) : (
<Redirect to="/login"/>
)
}
/>
)
}
Upvotes: 0
Reputation: 15688
Your set up seems good! Only thing I would note is that you're using <Router>
to wrap your routes in one file. And then nesting that same Router in another file with BrowserRouter
. This seems a bit duplicate.
Upvotes: 2