SolidJSS
SolidJSโ€ข3y agoโ€ข
9 replies
zh0nb

Array of components gets re-render every time that a new component is added

Hi, I'm struggling to allow users to add new inputs "on-the-fly" without forcing all elements to re-render (and therefore, losing their internal state). Not sure what I'm doing wrong, see the relevant part of my code below:
export default function RecipeForm() {
  const referenceForm = () => (
    <div class="mb-2">
      <FormInput
        type="text"
        name="references[]"
        label="Reference"
        autocomplete="off"
        required={false}
      />
    </div>
  );

  // References
  const [references, setReferences] = createSignal<Component[]>([]);
  // Add initial element
  setReferences(new Array(1).fill(referenceForm));

  const increaseNumberOfReferences: JSX.EventHandler<
    HTMLButtonElement,
    MouseEvent
> = (e): void => {
    e.preventDefault();
    setReferences([...references(), referenceForm]);
  };


  return (
    <>
    <Index each={references()}>
      {(reference, index) => <>{reference}</>}
    </Index>
    <button
      class="btn btn-accent"
      onClick={increaseNumberOfReferences}
    > 
      Add new recipe
    </button>
    </>
  )
}

any idea on how I could keep the state for the elements that didn't change? For now I'm just adding new elements into the array, but the idea is that I also allow removing them
Was this page helpful?