Search code examples
semantic-uireact-propscompositionreact-componentreact-class-based-component

Access Event Of Component That Is Passed As Prop


I pass a React Component as a Prop to a child. That component has an event. In child component, I want to get access to that event and bind it to a method inside child. How can I do that ?

I often use Semantic-UI React Modal as following:

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalOpen: false
        }
    }    

    handleOpen = () => this.setState({ modalOpen: true })

    handleClose = () => this.setState({ modalOpen: false })

    render(){
        return(
            <Modal 
                onClose={this.handleClose}
                open={this.state.modalOpen}
                trigger={<Button onClick={this.handleOpen}>Gandalf</Button>}>
                <Modal.Header>Balrog</Modal.Header>
                <Modal.Content>
                    <h1>You shall not pass!</h1>
                    {/* 
                    Some form that closes Modal on success
                    onSuccess : this.handleClose 
                    */}
                    <Button onClick={this.handleClose}>Grrrrr</Button>
                </Modal.Content>
            </Modal>
        )
    }
}

export default Example

Now I want to make it reusable

import React, { Component } from 'react'
import { Modal } from 'semantic-ui-react'

class ReusableModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalOpen: false
        }
    }    

    handleOpen = () => this.setState({ modalOpen: true })

    handleClose = () => this.setState({ modalOpen: false })

    render(){
        return(
            <Modal 
                onClose={() => this.handleClose}
                open={this.state.modalOpen}
                {/* 
                    How to access onClick event on trigger prop content ?  
                    this.prop.trigger can be a Button or a Menu.Item
                */}
                {...this.props}>
                {this.props.children}
            </Modal>
        )
    }
}

How can I have access to the trigger prop Component and bind its onClick event to handleOpen method ?

Edit :

to be more precise here is what I'm looking for

<ChildComponent trigger={<Button>This button should fire a function defined in child component</Button>} />


ChildComponent extends Component {
    functionToCall = () => { console.log('hello') }
    // I would like to :
    // let myButton = this.props.trigger
    // myButton.onClick = functionToCall
}

Solution

  • The key here is to clone element

    ChildComponent extends Component {
        functionToCall = () => { console.log('hello') }
    
        this.Trigger = React.cloneElement(
            this.props.trigger,
            { onClick: this.functionToCall }
        )   
    }