Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Prettiest way to dynamically load Component within Modal

I want to create a clean & reusable Modal-component like so:

var Modal = React.createClass({

  ....

  render: function() {
    return (
      <div className={ this.state.className }>
        <div className="modal-opacity" onClick={this.toggle}></div>
        <section className="modal-content">
          <a className="close" onClick={this.toggle}><img src="/images/icon-close.svg" alt="Close" /></a>
          <div>
            {this.props.module === 'curriculum' ? <Curriculum /> : <Contact /> }
          </div>
        </section>
      </div>
    );

To keep it neat — I'd would like to load the modal-content as a Component based on the {this.props.module} value, that is coming from the initiator component.

Is there a better way of doing this? Something like <{this.props.module}/>? Or is this insecure? Maybe there's is already something in ReactJS built-in?

like image 373
ricardo Avatar asked Aug 12 '15 13:08

ricardo


People also ask

How do you dynamically load component in React?

In React, dynamically importing a component is easy—you invoke React. lazy with the standard dynamic import syntax and specify a fallback UI. When the component renders for the first time, React will load that module and swap it in.

When should I use componentDidUpdate method?

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated.

How do you create a dynamic modal in React?

Creating the Modal Component { render(){ //if show is set to false, don't render if (! this. props. show) { return null; } return ( <h1>Hello World</h1> ) } } //create trigger class Toggle extends React.

What is the best method to update state in component?

setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state.


1 Answers

You can use this.props.children to render component's child controls. Like this:

var Control = React.createClass({
    render: function() {
        return <div>{ this.props.children }</div>;
    }
});

var App = React.createClass({
    render: function() {
        return <Control><h1>child control</h1></Control>;
    }
});
like image 56
Tomasz Wiśniewski Avatar answered Oct 19 '22 23:10

Tomasz Wiśniewski