reza
reza

Reputation: 1776

get components by string names in ReactJS

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

Upvotes: 0

Views: 594

Answers (1)

Ajay Gaur
Ajay Gaur

Reputation: 5270

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.

Upvotes: 1

Related Questions