Ad

Reactjs - Is It Possible To Pass A Property To A Component As Following?

- 1 answer

wonder if it is possible to pass a component a property as following

ReactDOM.render(
    <ContainerBox anotherComponent={<AnotherComponent />} />, document.body);

And then insider the ContainerBox I want to pass AnotherComponent a property in following way.

class ContainerBox extends React.Component {
    clickHandler() {
         //does something fun
    }

    render () {
        return (
            this.props.anotherComponent(this.clickHandler) //<----- is it possible to pass properties from here?
        );
   }
}

Is it possible to pass things from ContainerBox to AnotherComponent from that position?

ContainerBox has a clickHandler function which I want to pass to AnotherComponent. It is possible to do so if I move <AnotherComponent /> to inside of render() instead. But then I cannot reuse ContainerBox for other components without first copying the whole ContainerBox.

Does it make sense? Hope you can understand.

UPDATED code example

Ad

Answer

Yes, that is possible. However, it's more common to do it like this

    ReactDOM.render(
    <ContainerBox><AnotherComponent /></ContainerBox>, document.body);

And in ContainerBox

class ContainerBox extends React.Component {
    render () {
        return (
            this.props.children
        );
   }
}

Read more about reacts this.props.children here: https://facebook.github.io/react/docs/multiple-components.html#children

Edit:

I just want to point out that in this example, we are not passing a component, but an element (the result of rendering the component).

It's also possible to pass components, like this:

<Foo buttonComponent={FancyButtonComponent} />

and in Foo:

render() {
    Button = this.props.buttonComponent;
    return (
        <div>
            ...
            <Button />
        </div>
    );
}
Ad
source: stackoverflow.com
Ad