Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

coding etude

[React(Ts)] select tag option 변경하기(초기화) 본문

ReactJs

[React(Ts)] select tag option 변경하기(초기화)

코코리니 2024. 3. 13. 02:17

select 태그를 통하여 값을 선택하려고 할때, 하나의 값 선택 후 중복값을 선택 하기 위해서 select 태그의 값을 초기화 해야 할때가 있다.

javascript를 사용한다면 event.target.option으로 쉽게 변경 할 수 있지만,

typescript를 사용할 때는 event가 어떤 유형의 이벤트 인지 타입을 설정해 주어야 하기때문에 부적확한 타입설정으로 인하여 설정이 안되는 경우가 있다.

 

가장 좋은 방법은 실제로 select 태그가 어떤 타입을 가지고 있는지 console에 직어 보면 가장 정확하다.

또한 HTML처럼 qureySelecter 를 react에서 사용하는것은 지양하고 있기 때문에 타입 설정 후 useRef를 사용하여 태그를 임시 저장해 두었다가 useRef를 활용하여 변겨해 주는 것이 좋다.

 

아래 예시는 slelect태그의 타입과 값을 강제로 변경 하는 코드이다.

function example() {
	const selectRef = useRef<HTMLSelectElement>(null);
    const [selectValue, setSelectValue] = useState<string>("");
    const [valArr, setValArr] = useState<string[]>([]);
    
    useEffect(() => {
    	if(selectValue.length !== 0){
        	setArrValue();
        }
    },[selectValue]);
    
    function onChangeSelect (e: React.ChangeEvent<HTMLSelectElement>):void {
    	e.preventDefault();
        setSelectValue(e.target.value);
    }
    function setArrValue():void {
    	//useState의 불변셩을 위한 방법으로 array값을 대입할때 사용하면 오류 없이 사용가능.
    	setValArr(data => {
       		let newData = [...data, selectValue];
            return newData;
        });
        // ref를 이용하여 옵셥값을 강제로 변경해 준다.
        selectRef.current.option.selectedIndex = 0;
        setSelectValue("");
    }
    
    return (
    	<>
        	<select name={"name"} ref={selectRef} onChange={onChangeSelect} defaultValue={""}>
            	<option defaultChecked value={""}>선택사항</option>
                <option value={"tom"}>tom</option>
                <option value={"mike"}>mike</option>
            </select>
        </>
    )
}

 

 

select 사용하기 생각보다 복잡하지 않다. 타입설정에서 해메이지 않는다면..

 

끝!