Search code examples
reactjsreact-routermaterial-designnavigateurl

Navigate to another page using Material SearchBar


I am using a Material SearchBar in the header of my app, and trying to navigate to a page '/search' on localhost onRequestSearch. The code for the search bar itself is simple:

 <SearchBar
   onChange = {() => console.log('onChange')}
   onRequestSearch = {() => this.setRedirect()}
   style = {{ margin: '0 auto', maxWidth:800}}/>

Now, I've tried implementing setRedirect function in a number of ways with no luck. First, I simply tried:

setRedirect() {
  this.props.history.push('/search');
}

But this gives an error of Undefined is not an object (evaluating this.props.history). I do have a Route set up for "/search" page in my main app. I also tried using Redirect:

constructor(props) {
  super(props);
  this.state = {
     redirect = false
    }
}

setRedirect()  {
  this.setState({
    redirect: true  
  }
}

And in the render method:

render() {
  if(this.state.redirect)  {
    return (
        <Router>
          <div>
            <Redirect push to="/search"/>
            <Route path="/search" exact strict component={Search}/>
          </div>
        </Router>
    );
   }
  else {
   // return other stuff
 }
}      

This simply results in the entire page going blank when I type something in the search bar and hit enter. The address in the browser does NOT change to '/search' either. Not sure what I'm doing wrong. Simply trying to navigate to another page once user enters text in the search bar and hits enter. Any suggestions will be greatly appreciated. Thank you in advance!


Solution

  • Try to add withRouter HoC and then try again with this.props.history.push()

    import {  withRouter } from 'react-router-dom'
    ...
    export default withRouter(MyComponent);