I have a few react components (for eg:like below)
import AloneTab from './tab/AloneTab'
import BiTab from './tab/BiTab'
import CalTab from './tab/CalTab'
import DelTab from './tab/DelTab'
I have an array obj={"Alone":true,"Bi":true,"Cal":false,"Del":true}
Currently, I am rendering the components inside a div
like so (just a representation)
<div>
{obj["Alone"]? <AloneTab/>: null}
{obj["Bi"]? <BiTab/>: null}
{obj["Cal"]? <CalTab/>: null}
{obj["Del"]? <delTab/>: null}
</div>
3 components will render ( will not render since "Cal":false
)
I have just shown only a few components but there are many more & repeating the code again & again is not nice. Is there a way to loop over the items & renders the components?
I tired
const keys= Object.keys(obj)
const values= Object.values(obj)
const tabs = keys.map((tab, index)=>
values[index] ? <`${tab}Tab`/> :null)
<div>
{tabs}
</div>
However, this does not work. Is there anyway to make this work?
2
Answers
Nope, unless you import all those components from a single file, you can’t render it from a string.
The only option is to define a mapping from key to React component, then you can get the Component based on the name
Example:
If you could change your import to get all those Tab’s from a single file:
You could use that as the mapping:
One method of making this work is to store the component within the object and associate it with the relevant key. Store this along with the boolean value of whether or not it should be shown.
Please see below:
The above returns: