React
<select> 시간 <-> 분 구현, Km <-> Mile
펭토리
2022. 7. 18. 13:41
<select>, <option> 태그를 사용해 시간 분 변환과 Km Mile 변환을 할 수 있는 페이지를 구현해보았다.
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
</body>
<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>
<script type ="text/babel">
const root = document.getElementById("root");
function MinutesToHours() {
const [amount, setAmount] = React.useState(0);
const [flipped, setFlipped] = React.useState(false);
const onChange = (event) =>{
setAmount(event.target.value);
}
const onClick = () => {
//setCounter(counter + 1);
setCounter((current) => current + 1);
};
const reset = () => setAmount(0);
const onFlip = () => {
reset();
setFlipped((current) => !current);
}
return(
<div>
<div>
<label htmlfor = "minutes">Minutes</label>
<input value = {flipped ? amount*60 : amount} id ="minutes"
placeholder ="Minutes" type ="number"
onChange = {onChange}
disabled={flipped}/>
</div>
<h4>You want to convert {amount}</h4>
<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}>Flip</button>
</div>
);
}
function KmToMiles() {
return <h3>KM 2 M</h3>;
}
function App() {
const [index, setIndex] = React.useState("xx");
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>
<hr/>
{index === "xx" ? "Please select your units" : null}
{index === "0" ? <MinutesToHours/> : null}
{index === "1" ? <KmToMiles /> : null}
</div>
);
}
ReactDOM.render(<App/>, root);
</script>
</html>
실행화면