React Router programmatic navigation issue solved.
Today, I spent couple of hours to fix the programmatic routing between components in react app.
When we specify route using “Route, BrowserHistory and Switch” components, we specify some routes as follows:
<BrowserRouter>
<Switch>
<Route path=“/signin” exact component={SignIn} />
</Switch>
</BrowserRouter>
Here, my SignIn component renders when user clicks on signIn link. Above given route takes care of routing to SignIn component.
Problem Faced:
My SignIn component has child components “form and form-fields”. Actual, form submit ishappening in child component. On the success of submit, I was trying to route to another component from child component. This kept failing.
Solution:
When we define <Route path... and renders component, that component receives various helper properties. One of that property is to get programmatic navigation. But this property goes to the component which I render using <Route path... not to its child component. So, I need to provide a callback to my child component which will be called on the success of submit. Through this callback, I am able to get control back to my parent component which was rendered using <Route path.... From, where I can navigate to another component using “this.props.history.push(’/path’) “. Of course, this path should have been defined using <Route path=“/path” component={myComponent}>












