user9950960
user9950960

Reputation:

ReactJS - Redirect in main component

I want to redirect to other page with search results after submitting form (search bar feature).

I will usually redirect with return <Redirect to={'/search/' + this.state.value} /> in render(), but I can't now since I need to render entire site (search bar is in main component). I already tried this.props.history.push('/search/' + this.state.value) and this.context.router.history.push('/search/' + this.state.value) in place of comment but it doesn't work.

(Code simplified for clarity)

import React, { Component } from "react";
import {
  Route,
  NavLink,
  BrowserRouter
} from "react-router-dom";
import Search from "./Search";
import Autosuggest from 'react-autosuggest';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { value: '' };
    this.search = this.search.bind(this);
  }

  // react-autosuggest code

  search(e) {
    e.preventDefault();
    // Redirect to '/search/' + this.state.value
  }

  render() {
    return (
      <BrowserRouter>
        <div className="app">
          <div className="header">
            <form className="search-form" onSubmit={this.search}>
                {/* Autosuggest input which updates this.state.value */}
            </form>
          </div>

          <div className="main">
            <Route path="/search/:handle" component={Search} />
            {/* Other Routes */}
          </div>
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

Both this.props.history and this.context.router.history are undefined if I try to use them. <Redirect /> (obviously) can't be rendered instead of <BrowserRouter />

Upvotes: 1

Views: 88

Answers (2)

ravibagul91
ravibagul91

Reputation: 20765

You need to import Redirect from react-router-dom,

import {Redirect} frpm 'react-router-dom'

And usage,

search(e) {
    e.preventDefault();
    if(this.state.value){
        return <Redirect to={`/search/${this.state.value}`}
    }
}

Upvotes: 0

Bernardo Sunderhus
Bernardo Sunderhus

Reputation: 164

Have you tried using withRouter HOC to App, giving you access to history as a prop?

class App extends Component {
  // ...
  search(e) {
    e.preventDefault();
    this.props.history.push(`/search/${this.state.value}`)
  }
  // ....
}
export default withRouter(App)

Upvotes: 2

Related Questions