1

I am new to React and I'm having an issue with passing custom props to this.props.children. I have tried React.cloneElement and I can see the prop when I do a console.log in the class I created it but it gets lost when I try to past it. I don't know if maybe React-Router-Dom is doing something to cause the prop to not get passed. any help would be greatly appreciated.

I started this project using Create-React-App from GitHub. I have the following software installed.

"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.4",
"redux": "^3.7.2",

in App.js

render() {
 return (
  <Provider store={store}>
    <BrowserRouter> 
    <Switch>
      <Route exact path="/" component={LoginPage} />
      <Route path="/Login" component={LoginPage} />
      <RootPage>
        <Route path="/TestPage" component={testPage} />
      </RootPage> 
    </Switch>
   </BrowserRouter>
  </Provider>
 );
}

in RootPage.js (Parent)

render() {
    const { classes, theme, children } = this.props;

    var childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { doSomething: "Test String" }));

    console.log(childrenWithProps)
    return (
        <div>
           {childrenWithProps}
        </div>
    );
}

With the console.log above in RootPage.js I can see the prop "doSomething".

in TestPage.js (Child)

render(){
    const { classes, theme } = this.props;

    console.log(this.props)

    return (
        <div> 
        </div>
    );
}

in the above console.log in TestPage.js I dont see "doSomething" prop I passed.

Thank you for any help.

konekoya
  • 1,995
  • 2
  • 18
  • 30
user1184205
  • 703
  • 1
  • 6
  • 18

1 Answers1

0

Spread the props into TestPage component from Route component.

<RootPage>
  <Route path="/TestPage" render={props => <TestPage {...props} /> }/>
</RootPage>
Ritwick Dey
  • 15,128
  • 2
  • 22
  • 34
  • Thanks for the fast reply, I tried what you have and I was able to pass props from App.js, but I really need to pass them from RootPage.js. Root page has the functions that TestPage needs to call. Maybe I'm missing something, is there a way to do that using what you have above? – user1184205 May 15 '18 at 04:48
  • I think, you're missing my point. I've edited the answer. Verify again. – Ritwick Dey May 15 '18 at 05:06
  • I am new to React not to mention the whole web developer thing. I understand that if I had functions and state in my App.js file where the routes are declared I could use what you have. I just can't understand how to fire off a function that lives in RootPage.js from TestPage.js with the above code. The RootPage will be where my header and side nav bar are at, thus the need for functions to be called in it. If I am missing something can you please point me in the right direction to learn it. Should I move those functions to app.js? – user1184205 May 15 '18 at 05:28