SixtyEight
SixtyEight

Reputation: 2490

How can I render my component X amount of times based on a selector?

I've got a "select" component that selects the number of forms I want to display below. The form is a single component and I want to reuse it. It needs do have an independent state so I can use how many fields I want for the same form (an array of fields). Any hints about How can I render this component multiple please?

const indexes = [1, 2, 3];

const MyComponent = () => {
  const [numberOfUnits, setNumberOfUnits] = useState(1);

  const Form = () => <p>my form</p>;

  return (
      <select onChange={e => setNumberOfUnits(e.target.value)}>
        {indexes.map(index => (
          <option key={index} value={index}>
            {index}
          </option>
        ))}
      </select>

    //Here I should render X (numberOfUnits) amount of times of the Form component 
  );
};

Upvotes: 0

Views: 168

Answers (1)

Branko Zivanovic
Branko Zivanovic

Reputation: 172

import React, { useState } from "react";
import ReactDOM from "react-dom";

const indexes = [1, 2, 3];

const MyComponent = () => {
  const [numberOfUnits, setNumberOfUnits] = useState(1);

  const Form = () => <p>my form</p>;
  const formElements = [];
  for (let i = 0; i < numberOfUnits; i++) formElements.push(<Form />);

  return (
    <React.Fragment>
      <select
        onChange={e => setNumberOfUnits(e.target.value)}
      >
        {indexes.map(index => (
          <option key={index} value={index}>
            {index}
          </option>
        ))}
      </select>
      {formElements}
    </React.Fragment>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

Upvotes: 1

Related Questions