1

I tried to pass in props to this.props.children using the following code

export default class Home extends Component {
     render(){
var children = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
  foo: "1"
})
});
       return(            
         <div className="bla">
            <h1>WeDate</h1>
            <div className="child">
             {children}
        </div>)
     }

}

But I can't read this.props.foo in my searchDate component when it renders normally. The following is my react router.

render(
    <Router>
        <Home>
            <Switch>
                <Route exact path="/"><Redirect to="/search" push/></Route>
                <Route exact path="/search" component={SearchDate}></Route>
            </Switch>
        </Home>
    </Router>
    ,document.getElementById('app')
);

1 Answers1

0

the children to your Home component are not the Routes but the Switch and hence foo is not passed down as props to the respective components. What you need to do is to nest your Routes is the Home component and not as children

Home

export default class Home extends Component {
     render(){
       return(            
         <div className="bla">
            <h1>WeDate</h1>
            <div className="child">
             <Switch>
                <Redirect from="/" exact to="/search"/>
                <Route exact path="/search" render={(props) => <SearchDate foo={'1'} {...props}/>}>
            </Switch>
        </div>)
     }

}

Routes

render(
    <Router>
        <Home />
    </Router>
    ,document.getElementById('app')
);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thanks. But how can I pass down additional props to the component in this case? – Licheng Luo Mar 27 '18 at 07:30
  • Check the updated answer and this https://stackoverflow.com/questions/44255415/passing-custom-props-to-router-component-in-react-router-v4/44255850#44255850 – Shubham Khatri Mar 27 '18 at 07:30