usser441251343234 usser441251343234 - 18 days ago 5
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

alert()
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.

<div>
<BunchOfComponents />
<MoreComponents />

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


And then make it show by controlling its
open
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 = (
<MyAlert
open={true}
msg="Hello World"
/>
)
DOM.findNode('someID').insert(alert); <-- fake API obviously
}


Is it possible to dynamically append components like that?

Answer

This is the dirty way I do it at work (that didn't sound right...) http://codepen.io/matthsiung/pen/JKOpVW

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');
  ReactDOM.render(
     <Dialog container={div}/>,
     document.body.appendChild(div)
  );
} 

Dialog component:

//When your dialog component closes it unmounts itself
close(){
  ReactDOM.unmountComponentAtNode(this.props.container);
},

//Before unmount it cleans up after itself by removing the dummy div   
componentWillUnmount() {
 document.body.removeChild(this.props.container); 
},