React MUI(Material UI) Dynamic Textfield

이경은·2021년 12월 3일
0
post-thumbnail

Dynamic Textfield

사용자가 원하는 대로 컴포넌트를 추가하고, 삭제할 수 있도록 구현하고자 한다.

add, remove button 추가

컴포넌트를 원하는 만큼 추가하고 제거할 수 있도록 하는 버튼을 추가한다.

                  <IconButton
                    disabled={fotaImages.length === 1}
                    onClick={() => handleRemoveFields(fotaImages.id)}
                  >
                    <RemoveIcon />
                  </IconButton>
                  <IconButton
                    disabled={fotaImages.length === 4}
                    onClick={handleAddFields}
                  >
                    <AddIcon />
                  </IconButton>

add, remove 함수 추가

  // Add Dynamic textfield
  const handleAddFields = () => {
    setFotaImages([...fotaImages, { fileName: "", componentId: "", imageId: "" }]);
  };

  // Remove Dynamic textfield
  const handleRemoveFields = (id) => {
    const values = [...fotaImages];
    values.splice(
      values.findIndex((value) => value.id === id),
      1
    );
    setFotaImages(values);
  };

실행 화면


참고 자료

https://github.com/candraKriswinarto/dymanic-form/blob/a142715acb4a4bb6eef177b918e7e0574cdf6c96/src/App.js#L46

profile
Web Developer

0개의 댓글