Skip to content

Instantly share code, notes, and snippets.

@ajl100b
Last active February 21, 2019 14:21
Show Gist options
  • Save ajl100b/51970eb09e59421a6c431f0c9f67b2eb to your computer and use it in GitHub Desktop.
Save ajl100b/51970eb09e59421a6c431f0c9f67b2eb to your computer and use it in GitHub Desktop.
Redirect to search results component upon submit of search terms from search bar embedded in a global navbar
import React, { Component } from 'react'
import { Redirect } from 'react-router'
export default class Search extends Component {
constructor () {
super();
this.state = {
fireRedirect: false
}
}
componentWillRecieveProps(nextProps) {
this.setState({ fireRedirect: false })
}
submitForm = (e) => {
e.preventDefault()
this.setState({ fireRedirect: true })
}
render () {
const { fireRedirect } = this.state
return (
<div>
<form onSubmit={this.submitForm}>
<button type="submit">Submit</button>
</form>
{fireRedirect && (
<Redirect to='/search-results'/>
)}
</div>
)
}
}
@oyeolamilekan
Copy link

You tried to redirect to the same route you're currently on: "/results" it showed me this error

@EthanCuiOU
Copy link

EthanCuiOU commented Aug 6, 2018

Thanks for providing this solution.
Using this, I can see my desired keyword changes in my url parameters. However, my component did not acatually update.
For example, if I'm currently on "url/search?keyword=a", and i search for b. The route will change to "url/search?keyword=b", but the page does not update and still shows the search results for 'a'.
Any idea why this happened?

BTW, I think the componentWillReceiveProps() method is deprecated. Consider replace it with componentDidUpdate per this React Doc:
https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

@Ridji
Copy link

Ridji commented Feb 21, 2019

Problem here is that react router doesn't replace component all the time.
So your Result component, or wherever you are redirecting, is rendered once, for the first time only.

To trigger changes on that Result component you should implement componentDidUpdate() method in Result component, with some code and logic that will trigger re-rendering.

For me solution was something like this

componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.location.search !== prevProps.location.search) {
        this.props.index(this.props.access_token, this.props.location.search);
    }
}

location.search is search query from input
It's set in Redirect component
<Redirect to={{pathname: '/search-results'/, search: '?term=' + this.state.term}}>

or in history.push on submitForm

submitForm = (e) => {
    e.preventDefault();
    this.setState({ fireRedirect: true });
    this.props.history.push({
        pathname: '/search-results',
        search: '?term=' + this.inputElement.current.value
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment