In this post, we will cover how to output an element n times in JSX in React. This isn’t as straight forward as we might think …

An example

Here’s a snippet of a component in React that needs to add a number of dynamic fields specified by the user:

const [
  inputfieldsToAdd,
  setInputfieldsToAdd,
] = React.useState(1);
const [
  committedFieldsToAdd,
  setCommittedFieldsToAdd,
] = React.useState(0);
return (
  <div>
    <div>
      <label>Number of fields to add</label>
      <input
        type="number"
        value={inputfieldsToAdd}
        onChange={(e) =>
          setInputfieldsToAdd(
            parseInt(e.currentTarget.value, 10)
          )
        }
      />
    </div>
    <button
      onClick={() => {
        setCommittedFieldsToAdd(
          inputfieldsToAdd
        );
      }}
    >
      Add fields
    </button>
    {/* TODO - add the dynamic fields */}
  </div>
);

We also have a Field component:

const Field = ({ id }: { id: number }) => (
  <div>
    <label htmlFor={`field${id}`}>Field {id}</label>
    <input id={`field${id}`} type="text" />
  </div>
);

So, we need to render Field, a number of times defined by the user.

#react #javascript

Repeating an element n times in React
42.55 GEEK