2

I have checked this link

So far, I'm not able to understand the handler part. So I was hoping for a more simple example perhaps?

Here is my main parent component:

class appTemplate extends React.Component {
    render() {
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {this.props.children}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}

What I want to do is pass down the prop this.props.route.path to my child components which is this.props.children.

I'm not really fully familiar with all the terms even though I've been touching React already for the last few months.

An example with a proper explanation would be greatly appreciated. Thanks.

Community
  • 1
  • 1
Joshua Rajandiran
  • 2,788
  • 7
  • 26
  • 53
  • that example is pretty old, checkout the latest docs.... if you use redux than just use connect wrapper, this will give you access to location and route anywhere in the app – abhirathore2006 Oct 15 '16 at 09:57

2 Answers2

6

The proper way to achieve that is using React.Children.map()

class appTemplate extends React.Component {
    render() {
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {React.Children.map(
                       this.props.children,
                       child => React.cloneElement(child,
                                   { 
                                      customProp: "Here is your prop",
                                      path: this.props.route.path
                                   })
                )}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}
QoP
  • 27,388
  • 16
  • 74
  • 74
0

React has a cloneElement function. The idea is to clone the children object, passing on path as a part of the props:

class appTemplate extends React.Component {
    render() {
        let children = null;
        if (this.props.children) {
          children = React.cloneElement(this.props.children, {
            path: this.props.route.path
          })
        }
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {children}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}

You should then be able to access the path using this.props.path within a child element, but (from what I remember) not from within elements nested within the child.

You can read more about cloning and passing values here: https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

Brian
  • 1,873
  • 16
  • 25