luki512
luki512

Reputation: 237

React dynamic components from JSON object

I'm searching for a shorter version to iterate through components from a JSON object ["Component1", "Component2", "Component3"] The Index should be the step number and the component should be outputted dynamically. Right now I have a static way, which will become very uncomfortable with more elements:

        <div">
            {step === 1 && <Component1 />}
            {step === 2 && <Component2 />}
            {step === 3 && <Component3 />}
        </div>

Does anyone knows a solution to this one?

Best regards!

Upvotes: 0

Views: 85

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

You can use an array or an object to map key to its value (the indexes are keys here):

const components = [<Component1/>,<Component2/>,<Component3/>]
<div>{components[step]}</div>

The above components invoked in the array (meaning, although only a single component used, all elements called React.createElement) , to resemble the conditional rendering save a function component instead:

const functionComponents = [() => <Component1/>, () => <Component2/>,() => <Component3/>]
const Component = functionComponents[step];
<div><Component/></div>

Upvotes: 1

Related Questions