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?

7
  • Do you want to pass a value through import? Commented May 29, 2018 at 17:28
  • Yes, that's exactly what I want to do! Commented May 29, 2018 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. Commented May 29, 2018 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 Commented May 29, 2018 at 17:35
  • take a look at this answer, i think you can make it work with a factory like this one stackoverflow.com/questions/29923879/… Commented May 29, 2018 at 17:36

1 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.