Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a React component as a prop

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?

like image 428
znat Avatar asked Apr 10 '17 20:04

znat


People also ask

How do I pass JSX as props?

You want to use JSX inside your props You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.

How do you pass a component as a prop in hooks?

In order to pass the isActive prop from the parent (MyCard) to the child (MyButton), we need to add MyButton as a child of MyCard. So let's import MyButton at the top of the file. import MyButton from "./Button"; Then, let's add MyButton as a child in the return statement of MyCard component.

Can a prop be a component?

Your own components can also use props . This lets you make a single component that is used in many different places in your app, with slightly different properties in each place by referring to props in your render function.


1 Answers

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>
    );
}
like image 193
Aren Hovsepyan Avatar answered Oct 02 '22 04:10

Aren Hovsepyan