How can I import a component or file in React using variables?

I am creating a web application using React that displays a project for a building of your choice on an already selected campus.

I have a Content component that loads a campus or building map, whichever you choose. The BuildingMap component should load a specific project according to the building you selected. It gets props.building with the building name, but I don't know how to load the component using that variable.

I've tried importing, extracting, and requiring, but nothing works.

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


source to share


2 answers


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

Depending on the number of buildings / drawings, you can import them one by one, create a component layout and select a component by creating an identifier.



If there are many / infinite components loaded, I would probably choose another method - I don't know the 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>
    )
  }
}

      

+1


source


To add to @ Andreyco's answer:

Using a lookup table for string IDs / names in component classes is a typical React idiom. One common use case is a modal manager component that can display several different types of modals. For some examples see Dan Abramov's answer in "How can I render a modal dialog in Redux?" (not specific to Redux) as well as some related articles in Modify Component Templates # Modal Dialogs and Redux Techniques # UI under React / Redux Reference List .



Per @azium comment: you can use dynamic imports (via require.ensure()

or a new function import()

) to load chunks at runtime, and you can add exports from those dynamically imported chunks to the lookup table when they are loaded.

+1


source







All Articles