728x90
리액트 단위 변환기 만들기
<!DOCTYPE html>
<html lang="en">
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
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"
onChange={onChange}
disabled={!inverted}
/>
</div>
<button onClick={reset}>Reset</button>
<button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
</div>
);
}
function KmToMiles() {
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="km">Km</label>
<input
value={inverted ? amount * 1.609 : amount}
id="km"
placeholder="Km"
type="number"
onChange={onChange}
disabled={inverted} />
</div>
<div>
<label htmlFor="miles">Miles</label>
<input
value={inverted ? amount : amount / 1.609}
id="miles"
placeholder="Miles"
type="number"
onChange={onChange}
disabled={!inverted}
/>
</div>
<button onClick={reset}>Reset</button>
<button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
</div>
);
}
function App() {
const [index, setIndex] = React.useState("x");
const onSelect = (event) => {
setIndex(event.target.value);
};
return (
<div>
<h1>Super Converter</h1>
<select value={index} onChange={onSelect}>
<option value="x">Select your units</option>
<option value="0">Minutes & Hours</option>
<option value="1">Km & Miles</option>
</select>
<hr />
{index === "x" ? "Please select your units" : null}
{index === "0" ? <MinutesToHours /> : null}
{index === "1" ? <KmToMiles /> : null}
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
</script>
</html>
728x90
'개발 > React' 카테고리의 다른 글
[React/Typescript] React와 socket.io 연결하기 (0) | 2023.09.08 |
---|---|
[React/Typescript] React와 Express 연동하기 (Get, Post) (0) | 2023.09.01 |
[React] exceljs 사용법 정리 (예제 포함) (0) | 2023.04.10 |