React is a Javascript library for building user interfaces developed by facebook.React can be used for developing single-page and mobile applications.These are the web apps that don’t need whole page reload on change of a view.
In the React community, React router is a library for handling routing.The routes are the components, which will be rendered into the browser once the app is running.
In this article you will learn how to create a custom router in the react-router.
You can refer the files provided in this
https://github.com/KtreeOpenSource/ReactExamples/tree/master/Custom_router_for_reactRouter
Step 1: Install React Router
Install react-router-dom into an existing react js application using this command
1npm i react-router-dom
Step 2: Custom Router Component
Define the routes like below.For example consider a AuthPermissionRoute which gives permission to the particular roles specified and gives error if the user is Unauthorized.
1export class AuthPermissionRoute extends React.Component {2 render() {3 let { component: Component, ...rest } = this.props4 return this.state.render ? (<Route5 {...rest}6 render={props =>7 this.state.authenticated ? (8 <Component {...props} />9 ) : (10 <Redirect11 to={{12 pathname: '/',13 state: { from: props.location, msg: "Unauthorized" }14 }}15 />16 )17 }18 />) : false19 }20}21<AuthPermissionRoute /> component will check all permissions and then redirect the user to the specified url22class AppRoutes extends Component {23 render() {24 return (25 <Switch>26 <AuthPermissionRoute exact path={'/help'} component={Help} />27 {/* add n number routes in this switch statement */}28 </Switch>29 )30 }31}32export default withRouter(AppRoutes)



