score:1

Accepted answer

One way of going about it is to add a componentDidUpdate lifecycle hook to the SearchPage component and check if the term parameter changes and do the search again.

If you want to remount the component when the term parameter changes instead, you can use the key prop to unmount the previous component and mount a new one when the key changes.

<Route
  path={"/search/:term"}
  render={props => <SearchPage key={props.match.params.term} {...props} />}
/>

score:1

Use the Link from react-router-dom instead of the <button> to change the route instead of just redirecting. Then in the onClick of the <Link> component call the fetchData and set the state accordingly.

<Link className="btn" to={"/search/"+this.state.text} onClick={this.handleOnClick}>Search!</Link>

Then in the handleOnClick function

handleOnClick() {
   this.setState({
      loading: true
   });
   fetchData(this.state.text).then(jsonResponse => {
     this.setState({
        loading: false,
        data: jsonResponse
     });
   });
}

Related Query

More Query from same tag