1

I have an array full of components called "componentPack". I'm trying to figure out how to render a certain component based on its index in the array.The part that is giving me trouble is rendering the component in JSX. To solve the problem I am using an intermediate array called "stager" that I push one component to and then map from:

var comp = stager.map((Component) => {
  return <Component />;
});

Is there anyway to pick a component directly from the original array?

Something like:

var comp = () => {return <{componentPack[3][2]} />;}

I feel as tho I do not really understand how JSX works in this case. Any help is greatly appreciated.

2 Answers 2

2

You can just opt for conditional rendering from the map component like

var index = 3;
const component = componentPack.map((Component, idx) => {
    if(idx === index) {
         return <Component/>
    } else {
         return null;
    }
})

then your can just render it like

render() {
    return (<div>{component}</div>);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can reference the jsx object directly. For example if you componentPack is an array of components like so:

const componentPack = [1, 2, 3, 4, 5].map((item) =>
  <Component/>
);

You can reference any individual element and get the specific component like:

render(){
  return componentPack[2] //Will return the third Component
}

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.