[React] input element 오류 및 게스트 체크

jiseong·2021년 9월 29일
0

T I Learned

목록 보기
86/291

A component is changing an uncontrolled input to be controlled

const [location, setLocation] = useState()

<input
  onChange={e => handleChange(e.target.value)}
  name="location"
  type="text"
  autoComplete="off"
  placeholder="어디로 여행가세요?"
  value={location && location}
/>

const [location, setLocation] = useState()에서 location 값이 undefined로 넘어와 input element에서는 uncontrolled input element로 인식을 해버렸는데 갑자기 location 값이 업데이트 되면서 value값이 변경되어 controlled input element로 전환되면서 생기는 오류였다.

이를 해결하기 위해서는 input element를 controlled input element로만 사용해야하는데 이는 간단하게 아래와 같이 해결하면 된다.

value={location || ''}

undefined 시에도 '' 공백을 넣어줌으로써 controlled input element로 인식하게 된다.

게스트 체크

에어비앤비에서 인원을 입력할 시 어린이 또는 유아는 성인 없이 이용할 수 없다라는 조건이 존재했다.

게스트관련 state를 이용하게 되면서 아래 두가지 조건을 이용하여 어린이 또는 유아가 보호자와 이용할 수 있게 하였다.

성인 0명일 때, 유아 또는 어린이를 증가시킬 때

const hasCompanion = () => guestNum.adult > 0;

const checkCompanion = grouptype => {
  if (hasCompanion()) {
    setGuestNum(prevState => ({
      ...prevState,
      [grouptype]: guestNum[grouptype] + 1,
    }));
  } else {
    setGuestNum(prevState => ({
      ...prevState,
      adult: 1,
      [grouptype]: guestNum[grouptype] + 1,
    }));
  }
};


if (grouptype === 'child' || grouptype === 'infant') {
  checkCompanion(grouptype);
}

성인 1명일 때, 유아 또는 어린이가 있을 시 성인을 감소시킬 때

const hasChildren = () => guestNum.child > 0 || guestNum.infant > 0;

if (grouptype === 'adult' && guestNum.adult === 1 && hasChildren()) return;

0개의 댓글