Routing is one of the toughest thing to Implement in Single Page App In React Ecosystem it is pretty much industry standard to use React Router to do routing. React Router have nice API and pleasant to work with but there few Issue that I faced while using React router
If you have declared component and it is not rendering It could be below three Issues.
- First, if you are using any state management solutions like Redux or Mobx if you have assigned different components to render in a different path like below we are using render function instead of the component both will do the same thing
If you click index("/") route link you will see routes URL is changed to "/about" but the corresponding component did not get render see below
the reason why it not rendering because redux only looks for state and props it not look for change in URL and renders component accordingly so to overcome we gonna use withRouter from React Router which injects history as props to the component now since history is added to this component whenever URL or history changes then component will rerender as props(history) is changed and will be able to see correct output
Solution:
- Route has one property called exact we normally use it to make sure mention component strictly renders to its exactly matched routes but exact one quirk in it, Declared component if had any nested components these won't render and surprisingly react router don't throw any error just won't render nested routes so just make sure whenever any nested routes is not rendering you might have used exact keyword on its parent component
as the example above "/test" and "/test1" route in Home component will never render because we have added exact while declaring the Home component so we want to make sure component declared on routes "/test" & "/test1" should render we would need to remove exact from its parent(home) component
Recommend Approach for adding Nested routes. In Path Property we usually hard-code path below it example of it
this is not correct practice it recommends to use match props which passed by React router to App component below is an example of it. we can simply use it and just add it here is we don't remember nested URL match.url take care of it we just need to add
trailing path which is specific to this route below is an example