0

I have a component that has some other components imported in for example:

import ComponentA from './components/ComponentA.js';
import ComponentB from './components/ComponentB.js';
import ComponentC from './components/ComponentC.js';
class Main extends Component {
...

then I have a function inside the main component named returnChild(String childName) that gets a string input, for example ComponentA or ComponentB, and returns the Component Object.

now I'm using a switch case to do it but components are too many and my source is messy. is there any way to get the value by string name in reactJS? For example:

returnChild = (childName) => {
    return get_value_by_name(childName)
} 
1
  • 3
    Can you elaborate on why you need the string? Add in ur Main code. Commented Apr 23, 2018 at 7:14

1 Answer 1

1

You can make a config of components and then return the component based on config. e.g.,

import ComponentA from './components/ComponentA.js';
import ComponentB from './components/ComponentB.js';
import ComponentC from './components/ComponentC.js';
....

const STRING_TO_COMPONENTS = {
    'componentA': componentA,  //the key is a string and value is a component object
    'componentB': componentB,  
    'componentC': componentC,  
    ....
}

and while using, you can use it something like this

returnChild = childName => STRING_TO_COMPONENTS[childName];

That would be the neatest method I know.

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

4 Comments

no. I dont want to duplicate the names. I want to make it dynamic
That is dynamic and you're not creating duplicate names. You're just making an object which "dynamically" will give you the component. Also, please comment the solution if you find anything better.
I didn't found any good solution. for "dynamically" I meant when a new component is added to components directory. I don't have to its name serveral times
Because there isn't any better solution. If there were, someone would've answered your question :)

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.