0

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.

manish thakur
  • 760
  • 9
  • 35
  • 76
  • Something similar was asked here: https://stackoverflow.com/questions/52621169/react-props-should-i-pass-the-object-or-its-properties-does-it-make-much-diffe – MalwareMoon Jan 04 '23 at 18:02
  • 1
    Don't use the index as `key`: https://stackoverflow.com/a/59518082/5767484 – NotX Jan 04 '23 at 18:34

1 Answers1

1

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.

As follow up for comment:

Because you essentially have one extra component, that could contain an error. It's not insane difference, but it's something to mention. Mostly it would come down to better control over it and flexibility of that component, because if you were to have condition for something in data, you could have it in that map instead of putting it into the <InputComp/> and making it less flexible.

Example of this would be:

// This is only mockup
data.map((item) => {
  if(item.name === "dog"){
    return <Input .../>
  }
}

Would mean that if you passed data you would do:

// This is only mockup
const Input = (props) => {
  if(props.data.name){
    return <input />
  }
  return <>
}

But what are you going to do, when you don't want to use it on dogs? Make another component? Pass controlling parameter? Remap data? At that point you can map inputs. It will bubble the code up for no reason.

MalwareMoon
  • 788
  • 1
  • 2
  • 13