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

npm 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.

export class AuthPermissionRoute extends React.Component {
render() {
let { component: Component, …rest } = this.props
return this.state.render ? (<Route
{…rest}
render={props =>
this.state.authenticated ? (
<Component {…props} />
) : (
<Redirect
to={{
pathname: ‘/’,
state: { from: props.location, msg: "Unauthorized" }
}}
/>
)
}
/>) : false
}
}
<AuthPermissionRoute /> component will check all permissions and then redirect the user to the specified url
class AppRoutes extends Component {
render() {
return (
<Switch>
<AuthPermissionRoute exact path={‘/help’} component={Help} />
{/* add n number routes in this switch statement */}
</Switch>
)
}
}
export default withRouter(AppRoutes)