javascriptreactjsreact-motion

How to load Component dynamically in reactjs?


I'm working on a Reactjs + React-motion project, in a "modal window" (let's say) I'd like to mount or load a component dynamically, if that's possible ?

My solution so far: I couldn't find a way, so it seems that it's easier to have the component in place, and hide it, then toggle a class or style on state change, revealing the hidden component and only after the "modal window" transition finishes.

Sharing some code below where it's easier to understand what I'm trying to do. There's no event handlers and most code was removed, but the onRest (the event callback when the animation finishes is exposed) and also the render fn.

class HomeBlock extends React.Component {

    constructor (props) {
        ...

    }

    ...

    motionStyleFromTo () {

        return {
            ...
        };

    }

    onRest () {

        // this is triggered when the Motion finishes the transition

    }

    render () {

        return (
            <Motion onRest={this.onRestCallback.bind(this)} style={this.motionStyleFromTo()}>
                {style =>
                    <div className="content" style={{
                        width: `${style.width}px`,
                        height: `${style.height}px`,
                        top: `${style.top}px`,
                        left: `${style.left}px`
                        }}>
                        [LOAD COMPONENT HERE]
                    </div>
                }
            </Motion>
        );

    }

}

export default HomeBlock;

Solution

  • You can achieve this quite easily. In this example I am rendering a component dynamically based on a prop:

    class MyComponent extends React.Component {
      propTypes: {
        display: React.PropTypes.bool
      },
      render() {
        return (
           <div>
             {this.props.display ? <ChildComponent /> : null}
           </div>
        )
      }
    }
    

    In your case you may want to use internal component state to mount or unmount the component.

    FYI there are cases where you might prefer or need to use style to hide components instead of destroying them. There is more about this in the React documenation. See the 'Stateful Children' section here: https://facebook.github.io/react/docs/multiple-components.html