score:1

Accepted answer

the question here is what you really mean by "load".

1) if what you mean by "load" means actually to only render a component that was statically imported (already declared in the beginning of the file), then all you have to do is set some default value on the state i.e. :

state = {
   rendercomponentx: false
}

and then on the dropdown change method change the state to true:

setstate({"rendercomponentx":true})

and inside render have a condition as :

{this.state.rendercomponentx && <componentx />}

2) if on the other hand what you want is really to dynamically load components then it's a bit more complicated :

you need to create a component that asynchronously loads other components. i normally create an array of randomkeys on the state of the component, at the constructor:

constructor(props) {
    super(props);

    // dynamic key generation for dynamic view loading
    let randomkeys = [];
    while(randomkeys.length < 10){
        let y = math.random()*10000;
        if(randomkeys.indexof(y) === -1) randomkeys.push(y);
    }
    this.state = {
        randomkeys
    };
}

so that each of the new imported components will have a different key. in this case it's hardcoded to 0 but if you want to make this inside an iterator, you would have to create a variable to act as a counter to keep updating the index such as randomkeys[i] where i needs to grow from 0 to the length of components you want to import. also you need to make sure to generate enough keys in the constructor; this one is only generating 10, because this was for manual import, not within an iterator.

<asynccomponent key={this.state.randomkeys[0]} getcomponent={() => import('../login/login.js')} />

and my asynccomponent looks like this :

import react from 'react';
import proptypes from 'prop-types';

export default class asynccomponent extends react.component {

    state = {
        asyncmodule: null,

    };

    componentdidmount() {
        let that = this;
        this.unmounted = false;

        this.props.getcomponent()
        .then(module => {
            console.log("asynccomponent loaded module:",module);
            return module.default;
        })
        .then(asyncmodule => {
            if(that.unmounted!==true) {
                that.setstate({asyncmodule})
            }   
        });
    }

    componentdidupdate() {

    }

    componentwillunmount() {
        this.unmounted = true;
    }

    render() {
        const {loader, ...childprops} = this.props;
        const {asyncmodule} = this.state;

        if(asyncmodule) {
            return (<asyncmodule {...childprops} />)
        }

        if(loader) {
            console.log('loader = ',loader);
            return <div>loading...</div>;
        }

        return null;
    }
}

asynccomponent.proptypes = {
    getcomponent: proptypes.func,
    loader: proptypes.element
};

Related Query

More Query from same tag