grhmstwrt
grhmstwrt

Reputation: 341

import dynamic components in reactjs

fairly new to react.js, but prototyping a concept and getting stuck.

I want to have a component that delivers a variable name back (that it gets from an API), then based on that name, import a bunch of files that would share the same name in a folder structure, i.e.;

Folder structure

src/components/test/comp1.js
src/components/test/comp2.js

Then in my App component

import GetName from './components/apiRequest.GetName';
import Comp1 from './components/<GetName />/comp1';

Were GetName would deliver 'test' - But i can't do this, i just get a 'failed to compile' - any ideas on where i'm going wrong?

Upvotes: 2

Views: 377

Answers (1)

Karim
Karim

Reputation: 8652

The way you suggested won't work because GetName will return a React Component not a plain string that you can interpolate.

Assuming that you have a function GetName that returns a plain string rather than a component you can use the require api for a dynamic import.

//external module
function GetName(){
 //here you put your logic to return the name
 return "MyComponent";

}

and

class App extends Component {
  //App component
  render(){
    const myComp = require(`./components/${GetName()}`).default;
  }

}

Upvotes: 1

Related Questions