2

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?

grhmstwrt
  • 311
  • 1
  • 2
  • 17
  • Do you want to pass a value through import? – Bruno Mazzardo May 29 '18 at 17:28
  • Yes, that's exactly what I want to do! – grhmstwrt May 29 '18 at 17:29
  • Even if it is possible, I don't think it's a good way to do, if you don't mind I can try to show you other ways. – Bruno Mazzardo May 29 '18 at 17:31
  • Sure thing, suggest away. I basically want to load a set of HTML elements depending on the specific variable name I'm delivered back from our api. These would be physical HTML pages/ react components in separate folder structure, named the same as the variable I get back from api – grhmstwrt May 29 '18 at 17:35
  • take a look at this answer, i think you can make it work with a factory like this one https://stackoverflow.com/questions/29923879/pass-options-to-es6-module-imports?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Bruno Mazzardo May 29 '18 at 17:36
  • Normally we pass values through props, but the solution above should work – Bruno Mazzardo May 29 '18 at 17:37
  • If you want to do this to save some bandwidth, you can use webpack's [dynamic import](https://webpack.js.org/guides/code-splitting/#dynamic-imports) – Anton Harniakou May 29 '18 at 17:37

1 Answers1

1

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;
  }

}
Karim
  • 7,479
  • 1
  • 18
  • 31