Search code examples
javascriptreactjscomposition

How to pass callback functions to parent


Suppose we have a Container component as follows.

class Container extends React.Component {
    handleClose = () => {
        // need to ask 'Content' is it okay with closing
        const isContentAgree = /* */;
        if (isContentAgree) this.props.onClose();
    };

    render () {
        const {content: Content} = this.props;
        return (
            <button onClick={this.handleClick}>Close</button>
            <Content {/* some container-specific props */} />
        );
    }
}

Usage:

<Container content={SomeComponent}/>

In this scenario how can I pass a callback function from SomeComponent to Container? This callback is to be called when the button in the Container is clicked and returns a boolean value.


Solution

  • You need to keep isContentAgree in state and you can pass function to toggle isContentAgree to child component.

    class Container extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                  isContentAgree: false
                }
            }
    
            toggleContentAgree = (e) => {
                this.setState({ isContentAgree: e.target.value })
            }
    
            handleClose = () => {
                // need to ask 'Content' is it okay with closing
                const isContentAgree = this.state.isContentAgree;
                if (isContentAgree) this.props.onClose();
            };
    
            render () {
                const {content: Content} = this.props;
                return (
                    <button onClick={this.handleClose}>Close</button>
                    <Content toggleContentAgree={this.toggleContentAgree} />
                );
            }
        }