React Router v4 Redirect Passing State from Search to Results

14,707

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.

Share:
14,707

Related videos on Youtube

wsfuller
Author by

wsfuller

Front End Engineer that loves JavaScript, React, Redux, GraphQL, Node, and Boston Terriers

Updated on September 15, 2022

Comments

  • wsfuller
    wsfuller over 1 year

    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.

  • GeorgeButter
    GeorgeButter over 3 years
    How can you do this programmatically, like using useHistory?
  • Rohan Devaki
    Rohan Devaki almost 3 years
    if we use the state in redirect? then where are we going to extract it to use in a component?and how should we use it?
  • Helmer Barcos
    Helmer Barcos almost 3 years
    RohanDevaki and @Buts sorry but I answered this question more than 3 years ago. Please refer the docs for more info about it.