Home > Back-end >  How to Load a react components in an array and display them
How to Load a react components in an array and display them

Time:06-13

So I have a list of components that I want to load and store in an array

e.g array = [<component1/>,<component2/>,<component3/>,]

so this is my code and how I have structed everything to work

Declarations:

let components = []

Loading components into array:

useEffect(() => {
     for(let i=0;i<length;i  ){
      components[i] = <RadioButtonRN
      data={roadsigns.signs_questions[i].answers}
      box={false}
      textColor={primary}
      initial={2}
      selectedBtn={(e) => selectedAnswer(e)}
      />
     }
     connsole.log(components)
   },[])

Returning components for display:

return (
    <div>
     {components}
   </div>
  );
};

Somehow this code does load the component into the array but it doesn't display anything.

CodePudding user response:

try this

import React  from "react";

function App() {
  const compArray = () => {
    let arr = [];
    for (let i = 0; i < 3; i  ) {
      arr.push(<Name />);
    }
    return arr;
  };


  return <>{compArray()}</>;
}

export default App;

function Name() {
  return <h1>Hello world </h1>;
}

CodePudding user response:

You need to include a key for each component. I'm fairly certain it should work once you do this (assuming the trailing } after your return is the end of the function.

For a simple key assignment:

components[i] = <RadioButtonRN
key={i}
data={roadsigns.signs_questions[i].answers}
...
/>

CodePudding user response:

If you want array of same components,

return < > {
    components.map((el, i) => < Yourcomponent key = {
        i
      }
      otherParams = {
        el
      }
      />)} <
      />
  • Related