[React]State 사용해보기-3

2해승·2023년 1월 26일
0

니꼬쌤 State 강의 최종장!@

컴포넌트가 여러개 있을 때 html select를 이용하여 번갈아 노출시키는 법을 알아보자.

//각각의 스위치 함수를 만들어주고 여기서는 생략
function MinutesToHours()
function KmToMill()

function App() {
	const [index, setIndex] = React.useState("0")
    const onSelect = (event) => {
    	setIndex(event.target.value)
    }
    return (
    	<div>
        	<h1 className="h1">Super Converter</h1>
            <select value={index} onChange={onSelect}>
            	<option value="0">Minutes & Hours</option>
                <option value="1">Km & Miles</option>
            </select>
            <hr />
            {index === "0" ? <MinutesToHours /> : null}
            {index === "1" ? <KmToMill /> : null}
        </div>
    )
}

  • const [index, setIndex] = React.useState("0")
    event.target.value 값을 확인해보면 "0" 혹은 "1"로 확인된다. 즉 문자열이기 때문에 아래 삼항연산자에서 동일하게 index === "0"를 해주어야만 페이지를 처음 렌더할때부터 컴포넌트를 제대로 노출시킨다!

  • {index === "0" ? : null}
    {index === "1" ? : null}

    각각의 index 값에 맞는 컴포넌트를 노출시키고 아닌 것은 null 처리하여 안보이게 한다.
profile
Node 백엔드 개발자 / 데브옵스 취준생

0개의 댓글