0

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!

1
  • What does the JSON object look like? Is the property like { components: [Component1, Component2, Component3] }? Commented Sep 22, 2020 at 7:11

1 Answer 1

1

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>
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.