Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
    )
  }
}
like image 641
Carla Balbontin Avatar asked May 31 '17 21:05

Carla Balbontin


1 Answers

Unfortunately, you cannot import/require components dynamically in React environment.

Depending on how many buildings/blueprints there are, it's possible to import them one by one, create component-building map and pick component by building ID.

If there are many/infinite components to load, I would surely pick another method - don't know content of your problem.

import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...

class BuildingMap extends React.Component {
  render(){
    const C = {
      buildingA: BlueprintA,
      buildingB: BlueprintB,
      buildingC: BlueprintC,
      // ...
    }[this.props.building]

    return (
      <div className="blueprint" id={this.props.building}>
         <C />
      </div>
    )
  }
}
like image 179
Andreyco Avatar answered Sep 22 '22 22:09

Andreyco