TheWebs TheWebs - 2 months ago 14
React JSX Question

Can I pass props to the children via props.children React JS

So if I have a component with a render method that calls this.props.children to render out any children, can I pass any props from the parent to the children its trying to render?

For example, consider the following:

import React, { Component } from 'react';
import CoreSceneManager from '../engine/scene_manager';

export default class SceneManager extends Component {

constructor(props) {
super(props);
this._sceneManager = new CoreSceneManager();
}

componentWillMount() {
this._sceneManager.registerScenes(this.props.children);
}

componentWillUnmount() {
this._sceneManager.exit();
}

render() {
return(
<div>
{this._sceneManager.getCurrentScene()}
</div>
);
}
}


Used as such:

export default class SceneHandeling extends Component {

constructor(props) {
super(props)
}

render() {
return(
<Loop>
<SceneManager>
<ExampleSceneA />
<ExampleSceneB />
</SceneManager>
</Loop>
);
}
}


What we do is render only one of the scenes in the the scene manager, but as we can see in the scene manager component I have a "private variable" called
this._sceneManager
.

I would like to pass this to the children, in this case
ExampleSceneB
as thats whats being rendered to the page.

Answer

Yea all you need to do is clone the element with the additional props you want. like this.

componentWillMount() {
    const childrenWithProps = React.Children.map(this.props.children,
        (child) => React.cloneElement(child, {
            sceneManager: this._sceneManager
        })
    );
    this._sceneManager.registerScenes(childrenWithProps);
}