Alex Zhulin
Alex Zhulin

Reputation: 1305

Pass React Route to child component

I have my Routers function from which I can call my Home component like this

import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./containers/Home";
import NotFound from "./containers/NotFound";
import InputForm from "./containers/InputForm";
import Logout from "./containers/Logout";

export default function Routes() {
    return (
        <Switch>
            <Route path="/" exact component={Home}/>
            <Route path="/login" render={(props) => <InputForm {...props} buttonName={"Вход"} type={"login"} />}/>
            <Route path="/signup" render={(props) => <InputForm {...props} buttonName={"Регистрация"} type={"signup"} />}/>
            <Route path="/logout" exact component={Logout}/>
            <Route component={NotFound}/>
        </Switch>
    )
}

In my Home component I have connect to Redux storage like this

import React from "react";
import { connect } from "react-redux";
import Promo from "./Promo";
import Profile from "./Profile";

const mapStateToProps = state => {
    return { currentUser: state.currentUser };
};

const HomeConnected =({ currentUser }) => {
    if (currentUser.token === undefined) {
        return(
            <Promo />
        )
    } else {
        return(
            <Profile />
        )
    }

};

const Home = connect(mapStateToProps)(HomeConnected);
export default Home

In my Promo component I want to create redirect to some where in my application like this

import React from "react";
import Jumbotron from "react-bootstrap/lib/Jumbotron";
import Button from "react-bootstrap/lib/Button";

export default class Promo extends React.Component{
    handleRegisterClick = () => {
        this.props.history.push("/signup");
    };

    render() {
        console.log(this)
        return (
            <Jumbotron>
                <p>
                    <Button bsStyle="primary" onClick={this.handleRegisterClick}>Try this</Button>
                </p>
            </Jumbotron>
        );
    }
}

But got an error after clicking on button

   5 | 
   6 | export default class Promo extends React.Component{
   7 |     handleRegisterClick = () => {
>  8 |         this.props.history.push("/signup");
   9 |     };
  10 | 
  11 |     render() {

How can I pass Router to my child component?

Upvotes: 0

Views: 96

Answers (1)

Meet Zaveri
Meet Zaveri

Reputation: 3059

You can wrap that child component to withRouter HOC(Wrapper) which is provided by react-router-dom.

This provides acess to react-router API. That means you'll get all methods and props to it.

Jus wrap it with withRouter.

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

...

class Promo extends React.Component{

}

export default withRouter(Promo)

Upvotes: 3

Related Questions