score:0
What you can do is wrap your routes in what is called a composed component. It will check to see if your user is authenticated, if he/she is not, it will kick them back to whichever route you choose.
Here is an examples of a composed component, then I will show you how to use it in your routes file.
import React, {Component} from 'react';
import {connect} from 'react-redux';
export default function(ComposedComponent) { //This code right here serves as the base for any high order component
class Authentication extends Component {
static contextTypes = { //static creates a class level object that will give any other method in this component access to Authentication.contextTypes
router: React.PropTypes.object //This lets react know ahead of time we will use the router and it defines its type as object
}
componentWillMount() {
if (!this.props.authenticated) {
this.context.router.push('/signup');
}
}
componentWillUpdate(nextProps) {
//this lifecycle method runs when the component is about to update with new props, nextProps are those new properties for the rerender
if (!nextProps.authenticated) {
this.context.router.push('/signup');
}
}
//{...this.props} makes sure the new combined component Enhanced Component will have all the props of the original component passed into this function/Authentication class
//it maintains those props even though it's combining two components together to form a Enhanced Component
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
function mapStateToProps(state) {
return { authenticated: state.user.authenticated };
}
return connect(mapStateToProps)(Authentication);
}
I've imported the Authentication component above as RequireAuth in my routes file. It will check to see if a user is authenticated in my redux state. If the user is not authenticated, the user is kicked back to my '/signup' route. You cans see where that happens in the lifecycle methods of Authentication. Basically if I wrap any component in my routes with RequireAuth, those components will inherit its lifecycle methods. You can use it for more than just checking to see if they are logged in or not. You can have certain users with admin access etc. You just need to check the user's qualifications in the life cycle methods and push the route wherever you want.
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="inventory" component={RequireAuth(Inventory)} />
<Route path="signup" component={Signup} />
<Route path="single-product/:id" component={RequireAuth(Product)} />
<Route path="examples" component={Examples} />
<Route path="pricing" component={Pricing} />
<Route path="profile" component={RequireAuth(Profile)} />
<Route path="allProducts" component={RequireAuth(AllProducts)} />
<Route path="reporting" component={RequireAuth(ReportingContainer)} />
<Route path="signout" component={Signout} />
</Route>
);
score:1
After user login/signup you can change the state(eg this.setState({isLoggedIn: true}
) in your parent component( index.js or App.js ). Now based upon the state you can redirect the user to the desired location.
<Route path='/dashboard'
render={() =>
this.state.isLoggedIn ?
<Dashboard user={this.state.user} /> :
<Redirect to="/home"/>
}
/>
You can see the entire code here: link. Still if any doubts, ask in the comment section.
Source: stackoverflow.com
Related Query
- react separate routes for logged in and guest user
- React app using Laravel for API and user login. Question about retrieving currently logged in user from database
- Declaring React Routes in a separate file and Importing
- How to use Apollo Client + React Router to implement private routes and redirection based on user status?
- How to tell if a user is logged in with http only cookies and JWT in react (client-side)
- a better pattern for authenticated React components and routes
- React router briefly shows the login screen and then redirects to dashboard if user is logged in
- Possible to mix JSX and regular object for routes in React Router?
- What is different between React Context API and a separate JS file to store user data?
- How to move react event handlers to separate file ,export and then import for reuse in multiple different functional components?
- Passing all http requests and React Routes through node backend first for session verification and then return path
- Separate filter and sorting button for react table
- React: how to structure routes for admin, user and public
- Ionic React handle Hardware BackButton {Android or IOS } For Routes and any other Overlay component such as Modal, ActionSheet, etc
- How to default user state to logged in user Firebase and React
- React router dom add headers and dashboard for certain routes
- Managing static files Separately For Media Uploads and Separate for React Build
- Should I user separate routes or steps for multistep form in react?
- React Router - different header for Private and Public routes
- How to create user page for each user from react and firebase
- React searching for a user and rendering it out
- React - Difference between Wrapping Lazy Routes in 1 Suspense vs Separate suspense for each lazy route component
- how to render header, footer, menu, only once and only for private routes with react js?
- Redirecting to home page after login conflicts with removing protected routes for logged in users | React
- What is the best way to load and reuse api data for multiple routes in react
- How I can separate and dynamic set html template for react component?
- React conditional render for logged in / logged out User only updates state with browser refresh
- Redirect to dashboard on refresh if user is logged in React and Typescript
- How to correctly create a json response of a logged in user for react
- How to refactor react component separate for rendering and logic?
More Query from same tag
- Strange double execution of setState code in react
- Trying to save data in localStorage
- How to group an array of objects by value for the same item?
- react-native set global state and call back using redux
- Filtering a database based on checkboxes
- How to display all items from an API in React JS?
- How to store inCart value in localStorage?
- ReactJs: Load More pagination type (append)
- Can't access FormData using sign-up form from Material-UI example templates
- Keep components between routes using react-router
- Unknown prop `float` on <div> tag
- Store JSON in a variable in a REACT Helper component
- React router v4 redirect when no match
- change state using setstate
- Filtering an array of arrays with another array to return only combination of matching values
- Multiply values from two different input and show in the third input
- Multiple draftjs components with plugins at once
- What's Relay operation name?
- React Component not rendered
- dark area in react-vis example
- Trying to toggle between icon to text on my navigation using React
- Passing refs from Component to Component in React
- Passing user permission from child to parent component with ReactJS
- Line 105:14: 'accountSelector' is not defined no-undef
- Antd horizontal sub menu "floating"
- Material-ui Select component not update state correctly
- Render JSX element based on condition
- how to close the menu when clicked
- React-redux reselect performance
- React hooks add mapped checkbox values to array or remove it