frogatto
frogatto

Reputation: 29285

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.

Upvotes: 1

Views: 1848

Answers (4)

mukesh210
mukesh210

Reputation: 2892

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} />
            );
        }
    }

Upvotes: 1

indolentdeveloper
indolentdeveloper

Reputation: 1313

you can simply pass the callback function as prop to the component.

<Content onHide={handleClose} />

in Component you have to call props.onHide function as needed.

Upvotes: 1

Shlizer
Shlizer

Reputation: 115

You should do it using store (Redux/Mobx/ContextAPI). That's the ideal way to do it.

But...

You can still pass the callback function:

class Container extends React.Component {
    render () {
        const {content: Content, callback} = this.props;
        return (
            <button onClick={this.handleClick}>Close</button>
            <Content onSomething={callback} {/* ... */} />
        );
    }
}

<Container content={SomeComponent} callback={someCallbackFunction}/>

Upvotes: 0

user1452221
user1452221

Reputation: 124

You can use:

React.cloneElement(SomeComponent, [props...])

And as "props" to pass a function that updates container state.

Upvotes: 0

Related Questions