How to import a component or file in React using variables?

Viewed 15872

I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus.

I have a "Content" component that loads the campus or building map, depending what you chose. The "BuildingMap" component needs to load a specific blueprint according to what building you selected. It gets the props.building with the name of the building but I don't know how to load a component using that variable.

I have tried import, fetch and require but nothing seems to work.

Please help.

My code looks something like this:

//Content Component

<BuildingMap building={selectedBuilding} campus={selectedCampus} />

//BuildingMap Component

import *MyBlueprint* from (specific folder depending on the campus selected)

class BuildingMap extends React.Component {
  render(){
    return (
      <div className="blueprint" id={this.props.building}>
         {*MyBlueprint*}
      </div>
    )
  }
}
3 Answers

This question is pretty old but as I was looking for how to solve the same problem let me give my answer. It can be done with dynamic import React.lazy:

const OtherComponent = React.lazy(() => import('./OtherComponent'));

See more details here: https://reactjs.org/docs/code-splitting.html#reactlazy

Related