선택 필터를 위한 Custom Select 컴포넌트를 개발하면서 아래와 같은 Warning error 를 마주하였다.
Warning: client.js:1 Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.
Custom Select 컴포넌트 코드
import React from 'react';
export type optionType = {
label: string;
value: string | number;
};
interface SelectProps {
options: Array<optionType>;
isExistAll?: Boolean;
onChange: Function;
}
const Select = ({
options,
isExistAll,
onChange
}: SelectProps): JSX.Element => {
return (
<select
className='select w-full max-w-xs'
onChange={(e) => onChange(e.currentTarget.value)}>
{isExistAll && <option selected value={0} label='전체' />}
{options &&
options?.map((item: optionType) => (
<option key={item?.value} value={item?.value} label={item?.label} />
))}
</select>
);
};
export default Select;
선택하는 형식의 필터를 구현할 때는 주로 <select>...</select>
라는 태그의 children 으로 <option key={} value={} label={} selected/>
형식의 옵션 태그가 들어간다.
에러 내용을 따르자면 여기서 초기 option 값을 정의할 때 <option/>
태그에 selected 라는 prop을 사용하는 대신 <select defaultValue={<option 태그의 value property 값>}
또는 <select value={<option 태그의 value property 값>}
의 형식으로 대체하라는 경고 메세지였다.
따라서, 서론에 있던 컴포넌트 코드를 아래와 같이 수정하였다.
import React from 'react';
export type optionType = {
label: string;
value: string | number;
};
interface SelectProps {
options: Array<optionType>;
isExistAll?: Boolean;
onChange: Function;
}
const Select = ({
options,
isExistAll,
onChange
}: SelectProps): JSX.Element => {
return (
<select
className='select w-full max-w-xs'
onChange={(e) => onChange(e.currentTarget.value)}
+ defaultValue={0}
>
- {isExistAll && <option selected value={0} label='전체' />}
+ {isExistAll && <option value={0} label='전체' />} // 초기 option 선택값 (value: 0)
{options &&
options?.map((item: optionType) => (
<option key={item?.value} value={item?.value} label={item?.label} />
))}
</select>
);
};
export default Select;
수정한 결과 아래와 같이 더이상 Warning Error 가 발생하지 않았다.
<select>...</select>
태그로 select Filter 같은 형식의 컴포넌트를 만들 때, 초기 option 선택 값은 <option/>
옵션 태그에 직접 하는 것이 아닌 <select/>
에 defaultValue(또는 value) 프로퍼티 값으로 정의하도록 한다.