본문 바로가기

그 땐 Front했지/그 땐 React했지

[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 9. Final Practice and Recap

728x90

참고자료: 노마드 코더 ReactJS로 영화 웹 서비스 만들기 https://nomadcoders.co/react-for-beginners/lobby

1.  select로 본인이 원하는 단위 변환을 선택해보자!


이전 코드를 component로 만들기


function MinutesToHours() { 
    const [amount, setAmount] = React.useState(0);
    const [inverted, setInverted] = React.useState(false);

    const onChange = (event) => {
        setAmount(event.target.value);
    }
    const reset = () => setAmount(0);
    const onFlip = () => {
        reset();
        setInverted((current) => !current);
    };
    return(
        <div>
            <div>
                <label htmlFor="minutes">Minutes</label>
                <input 
                    value={inverted ? amount * 60 : amount} 
                    id="minutes" 
                    placeholder="Minutes" 
                    type="number" 
                    onChange={onChange}
                    disabled={inverted}
                />
            </div>

            <div>
                <label htmlFor="hours">Hours</label>
                <input 
                    value={inverted ? amount : Math.round(amount / 60)} 
                    id="hours" 
                    placeholder="Hours" 
                    type="number"
                    disabled={!inverted}
                />
            </div>
            <button onClick={reset}>Reset</button>
            <button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
        </div>
    );
};

function KmToMiles() {
    return(
        <h3>KM 2 M</h3>
    );
};

👉🏻이전에 App component에 있던 내용을 MinutesToHours component로 만들고 KmToMiles component를 추가한다.

function App() { 
    const [index, setIndex] = React.useState();
    const onSelect = (event) => {
        setIndex(event.target.value);
    }
    return(
        <div>
            <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" ? <KmToMiles/> : null}
        </div>
    );
}
  • select와 option으로 선택지를 만든다.
  • select tag의 onChange에 onSelect를 호출한다.
  • onSelect에서 선택된 option의 value를 inext state로 설정한다.
  • 마지막에 set된 index에 따라 다른 내용을 보여준다.

선택한 결과에 따라 다르게 나타남!

728x90