-
[ReactJS] 리액트로 분/시간, Km/Miles 변환기 만들기ReactJS 2022. 10. 5. 22:34
HTML 코드
<!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="root"></div> <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </body> </html>
아래는 리액트 코드
<script type="text/babel"> function MinutesToHours() { const [amount, setAmount] = React.useState(0); const [flipped, setFlipped] = React.useState(false); const onChange = (event) => { setAmount(event.target.value); }; const reset = () => setAmount(0); const onFlip = () => { reset(); // 현재의 값을 반대로 바꿔줌 setFlipped((current) => !current); }; return ( <div> <div> <label htmlFor="minutes">Minutes</label> <input // 외부에서도 input의 값을 수정해주기위해 이렇게 연결함. ex) reset value={flipped ? amount * 60 : amount} id="minutes" placeholder="Minutes" type="number" onChange={onChange} disabled={flipped} /> </div> <div> <label htmlFor="hours">Hours</label> <input value={flipped ? amount : Math.round(amount / 60)} id="hours" placeholder="Hours" type="number" disabled={!flipped} onChange={onChange} /> </div> <button onClick={reset}>Reset</button> <button onClick={onFlip}>{flipped ? "Turn back" : "Invert"}</button> </div> ); } function KmToMiles() { const [amount, setAmount] = React.useState(0); const [flipped, setFlipped] = React.useState(false); const onChange = (event) => { setAmount(event.target.value); }; const reset = () => setAmount(0); const onFlip = () => { reset(); // 현재의 값을 반대로 바꿔줌 setFlipped((current) => !current); }; return ( <div> <div> <label htmlFor="km">Km</label> <input // 외부에서도 input의 값을 수정해주기위해 이렇게 연결함. ex) reset value={flipped ? amount / 1000 : amount} id="km" placeholder="km" type="number" onChange={onChange} disabled={flipped} /> </div> <div> <label htmlFor="miles">Miles</label> <input value={flipped ? amount : amount * 1000} id="miles" placeholder="miles" type="number" disabled={!flipped} onChange={onChange} /> </div> <button onClick={reset}>Reset</button> <button onClick={onFlip}>{flipped ? "Turn back" : "Invert"}</button> </div> ); } 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="xx">Select your units</option> <option value="0">Minutes & Hours</option> <option value="1">Km & Miles</option> </select> {index === "xx" ? "Please select your units" : null} {index === "0" ? <MinutesToHours /> : null} {index === "1" ? <KmToMiles /> : null} </div> ); } const root = document.getElementById("root"); ReactDOM.render(<App />, root); </script>
'ReactJS' 카테고리의 다른 글
[React] 컴포넌트와 렌더링 (0) 2022.11.30 [React] ref란? (feat. DOM API를 쓰면 안되는 이유) (0) 2022.11.30 [ReactJS] useEffect, Cleanup (0) 2022.10.07 [ReactJS] props, memo (0) 2022.10.06 [ReactJS] useState (0) 2022.09.26