usser441251343234 usser441251343234 - 6 months ago 43
React JSX Question

How do you dynamically insert a React component into the DOM (for instance a dialog)?

I'd like to replace javascript's built in

function with a React Component that handles the same task: namely, showing a quick, dismissible message to the user.

Now, I can make this happen by creating a component and placing it in my markup. e.g.

<BunchOfComponents />
<MoreComponents />

<MyAlertDialog open={this.props.shouldShowAlert} />

And then make it show by controlling its
state via Redex or whatever.

However, what I'd like to do, it be able to not declare it in my markup and instead inject it into the dom via a function.

Something like...

myCoolFunction() {
const alert = (
msg="Hello World"
DOM.findNode('someID').insert(alert); <-- fake API obviously

Is it possible to dynamically append components like that?


This is the dirty way I do it at work (that didn't sound right...)

I'm sure there's a better 'proper' way to do it but it cleans up after itself so it works for me.

Here are the key points:

Dialog trigger

//Your trigger function will render the dialog component to a newly created dummy div,
// while also passing it into the component as a prop

function showDialog() {
  var div = document.createElement('div');
     <Dialog container={div}/>,

Dialog component:

//When your dialog component closes it unmounts itself

//Before unmount it cleans up after itself by removing the dummy div   
componentWillUnmount() {