Returning Another Component via Render Props

Let’s say you’re sending a button from a parent to a child using render props.  How do you properly render and place the returned button?

As it turns out, its quite easy.

Let’s say that this is your component which uses render props to return both the toggle state and the toggle button.

const React = require('react');

class ToggleProvider extends React.Component{
    constructor(){
        super();
        this.state = {
            toggle: false
        };
    }

    handleToggle = () => {
        this.setState({toggle: !this.state.toggle});
    };

    renderToggle = () => {
        return (
            <button onClick={this.handleToggle}>
                Toggle Me
            </button>
        );
    };

    render() {
        return this.props.children({
            buttonState: this.state.toggle ? "true" : "false",
            button: this.renderToggle()
        });
    }
}

module.exports = ToggleProvider;

To use the above provider, you may be tempted (because of patterns) to do this.

<ToggleProvider>{
    ({toggleButton, toggleState}) => (
        <div className='my-container'>
            <toggleButton />
            State: {toggleState}
        </div>
    )}
</ToggleProvider>

However, because the parent has already rendered the button, the child needs only to place the rendered component as if it were any other variable.

<ToggleProvider>{
    ({toggleButton, toggleState}) => (
        <div className='my-container'>
            {toggleButton}
            State: {toggleState}
        </div>
    )}
</ToggleProvider>

That’s it.

 

Leave a Reply

Your email address will not be published.