How to call a method from a component using Route in React Router v4?

1.2k views Asked by At

I have some nested routes written in react router v4 and in the Navigation component I have an input box.

On submit I need to call a method on a different route (on Landing component) and pass the value. I can't find any example to call a method in Route.

Any other way/ workaround to use a navigation with data and different routes is welcome.

My routes:

 return (
        <div>
            <Navigation callSearch = {this.callSearch.bind(this)} />
            <Switch>

                <Route path="/u/:slug" component={AuthorPage}/>
                <Route path="/:location/:slug" component={PhotoDetails}/>
                <Route path="/" component={Landing} />
            </Switch>
        </div>
    )

In Navigation i call callSearch() :

   searchPhotos(e) {
    e.preventDefault();

    if(this.state.searchTerm) {
        this.props.callSearch(this.state.searchTerm);
    }
}
1

There are 1 answers

0
Santosh Shinde On

I have fixed this issue in my application using withRouter from react-router module.

            import { Route } from "react-router-dom";
            import { withRouter } from "react-router";

            class SideBar extends Component {


            callSearch = (searchKeyword) => {

                if(searchKeyword)  this.props.history.push(`/u/${searchKeyword}`);

            };

            render() {
                return (
                    <div>
                        <Navigation callSearch = {this.callSearch} />
                        <Switch>

                            <Route path="/u/:slug" component={AuthorPage}/>
                            <Route path="/:location/:slug" component={PhotoDetails}/>
                            <Route path="/" component={Landing} />
                        </Switch>
                    </div>
                )
            }


            export default withRouter(SideBar);

Hope this will help anyone else !!!