If we pass the history object down into a component as props. Then we can navigate programatically using the react router methods available on the history object.
Now lets assume you are passing down the history object as a prop called 'router'. So it would be referenced inside a component with class based syntax like:
this.props.router
When using push or replace you can either specify both the URL path and state as separate arguments or include everything in a single location-like object as the first argument.
this.props.router.push('/some/path?the=query')
Or you can use a single location-like object to specify both the URL and state. This is equivalent to the example above.
On the page that is navigated to, the current location will be injected into the component whose route matched, so you can access the state using this.props.location.state.
One thing to keep in mind is that there will be no state if a user navigates directly to the page, so you will still need some mechanism to load the data when it does not exist.
I was not able to get this working with react-router v4+. But the following does work:
//I.e. add navigate using the history stack and pass context as the 2nd parameter
this.props.history.push('/takeTest', {
subjectsList: this.props.subjectsList.filter(f => f.isChecked === true)
})
Now in the second Component you can access the passed object as:
import React from 'react'
export default class Detials extends React.Component{
constructor(props){
super(props);
this.state={
value:this.props.location.state,
}
}
alertMessage(){
console.log(this.props.location.state.id);
}
render(){
return (
<>
{/* the below is the id we are accessing */}
hay! I am detail no {this.props.location.state.id} and my name is
{this.props.location.state.name}
<br/>
<br/>
{/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>
</>
)
}
}
note:In version 6 of react-router-dom the above method won't work on class components though you can use functional components of react by using useLocation hook and then you can draw the state object through that location in another component.
version 6
How to achieve the same using hooks v6 of react-router-dom
Let's suppose we have two functional components, first component A, second component B. The component A wants to share data to component B.