Home > Software engineering >  how to loop a reusable component using react
how to loop a reusable component using react

Time:01-05

I am working with react, and I came across one thing, which is looping through component

  • I have one inout field component which is generic.
  • when I have to create two input fields I am defining one data and looping the input component

My doubt

My doubt is shall I loop the input component where I am calling it, like below

{

inputData.map((li,ind)=>{
  return(
    <InputComp
    key={ind}
    type={li.type}
    name={li.name}
    id={li.id}
    className={li.className}
    />
  )
})}

Or shall I pass data as props and loop the inout field like below

<InputComp data={data}/> // calling the component

{data.map((li,ind)=>{ // inside component looping
  <input
  key={ind}
  type={li.type}
  name={li.name}
  className={li.className}
  />
})}

I am bit confused which is best over the other, my requirement can be of many types one is like above to create a normal input field the other can be to create dynamic input field I can have one button on click of which I have to add one new row and one more button to delete that row (row means input field)

SO I am writing this for better understanding for code, if there is one more option to create a input component I am open to use that code.

CodePudding user response:

I'd choose the first approach for following reasons:

  • You don't make another (probably single use) component just for rendering multiple input.
  • You are passing data as keyed props instead of the entire object, which makes it easier to debug and gives you more control over that component.
  • It makes your code stricter, which is better for having less mess in it.

Also remind you, that if you .map() elements, you should add key attribute to it.

CodePudding user response:

enter image description here

Please refer the below link for official docs.

https://reactjs.org/docs/react-api.html#reactchildrentoarray

  • Related