How to pass a React component as a prop

znat picture znat · Apr 10, 2017 · Viewed 10k times · Source

I'm using react-semantic-ui Modal object. The object that opens the modal is a prop.

 <Modal
       trigger=<Button>Text</Button>
       otherProp=...
   >
  </Modal>

I want to embed Modal in another component:

export default class Confirm extends Component {

    render() {
        return (
            <Modal
                trigger={this.props.trigger} /* here */
              >    
                <Modal.Content>
                    ...
                </Modal.Content>
                <Modal.Actions>
                    ...
                </Modal.Actions>
            </Modal>
        )
    }
}

How can I pass JSX code ( <Button>Text</Button> ) as a prop to be render as a Modal prop?

Answer

Aren Hovsepyan picture Aren Hovsepyan · Apr 10, 2017

You can easily do following

<Modal trigger={ <Button>Text</Button> }> 
   // content goes here 
</Modal>

and inside Modal, you can access it via this.props.trigger which will be your button component and you can render it like below

render () {
    return (
        <div>
            // some code can go here
            { this.props.trigger }
        </div>
    );
}