Have a Search component that when a payload comes back redirects to a Results component. Would like for that Results component to show the passed State of Search using React Router v4 Redirect. My assumption here from the Docs is that using state: { referrer: currentLocation }
an object can be passed.
Search
export default class Search extends Component{
constructor(props){
super(props);
this.state = {
searchValue: '',
results:[]
}
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleKeyPress = (e) => {
let searchParam = e.target.value;
if (e.key === 'Enter'){
axios
.get(URL+searchParam)
.then((response) => {
this.setState({results: response.data});
});
}
};
render(){
return(
<div>
<input
ref="search"
type="text"
placeholder="Search"
onKeyPress={this.handleKeyPress.bind(this)}
/>
{this.state.results.length > 0 &&
<Redirect to={{
pathname: '/results',
state: { results: this.state.results }
}} />
}
</div>
);
}
}
Results
export default class Results extends Component{
constructor(props){
super(props);
this.state = {
results:[] // <<<<<< Not sure if this needs set
}
}
render(){
console.log('SEARCH RESULTS STATE', this.state); // <<<< this either returns undefined or just an empty array depending if initial state is set
return(
<div>
<h1>Search Results</h1>
</div>
);
}
}
Unless I'm not reading into this correctly, the problem seems to be that when the Redirect happens there isn't anything being passed into the Results component.
If value is entered and is successful Redirect happens Search State returns Object {searchValue: "", results: Array(1)}
However Search Results state returns Object {results: Array(0)}
or undefined
depending on initial state setting.
Have also tried different component lifecycles on Results but unable to get any passed data that way. My thought there was maybe componentWillRecieveProps(nextProps, nextState){}
might be able to get some passed data and could have state set via those means.
at the beginning of the render() method from your main Class Component you have to code for example:
if (isLoggedIn){
return <Redirect to={{
pathname: '/anyPath',
state: { stateName: this.state.anyState}
}} />;
}
and in the component associated to the Route /anyPath
you have to extract the passed state calling this.props.location.state.stateName
. in your in your precise case you should call this.props.location.state.results
in the Results Class. You can delete the constructor method from your Results
class.
isLoggedIn
could be another state, that you could set to false at first in the constructor Method from your main component. Then isLoggedIn
could be set to true if your user clicks a button, and so you will redirect your app to another Route with preferred states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With