원하는 게임수를 입력하고 버튼을 클릭하면 지정 게임수 만큼 로또 번호를 출력하는 애플리케이션을 만들어 보겠습니다.
Lotto.js 파일을 만듭니다.
|
import { useRef, useState } from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import InputGroup from 'react-bootstrap/InputGroup';
import 'bootstrap/dist/css/bootstrap.min.css';
// 1게임의 로또 번호를 생성해 줌
let lottoGenerator = () =>{
let set = new Set();
while(set.size<6)set.add(parseInt(Math.random()*45)+1);
let ar = [...set];
ar = ar.sort((a,b)=>a-b);
return ar;
}
// 번호를 이미지로 출력해주는 컴포넌트
const Number = ({ number }) => {
let num = `${number}`.padStart(2, 0);
let src = `./images/numbers/ball_${num}.png`;
return <img src={src} alt={num} style={{ margin: "2px" }} />
}
// 로또 1게임 출력
const Lotto = ({lotto}) => {
return (
<div>
{
lotto.map((n) => <Number number={n} key={n}/>)
}
</div>
);
}
// 지정 게임수 만큼 로또 번호 배열을 만들어 줌
const makeLottos = (game)=>{
let lottos = [];
for(let i=0;i<game;i++){
lottos.push(lottoGenerator());
}
return lottos;
}
// 지정 게임수의 로또를 출력해 줌
export const Lottos = ()=>{
const inputRef = useRef(null);
const [value, setValue] = useState(5);
const [lottos, setLottos] = useState(makeLottos(5))
console.log(lottos);
const changeHandler = (e) => {
setValue(inputRef.current.value);
}
const clickHandler = (e) => {
setLottos(makeLottos(value));
}
const style = { fontSize:"1.5rem", marginRight:"15px"}
return (
<div style={{margin:"20px"}}>
<h2>로또 번호 자동 생성기</h2>
<InputGroup>
<span style={style}>몇 게임? </span>
<Form.Control type="number" value={value} ref={inputRef} onChange={changeHandler} min="1" max="20"/>
<Button variant="outline-success" onClick={clickHandler}>
로또번호 생성하기
</Button>
</InputGroup>
{
lottos.map((lotto)=> <Lotto lotto={lotto}/>)
}
</div>
)
}
|
App.js 파일을 만듭니다.
|
import { Lottos } from "./Lotto";
const App = ()=>{
return(
<>
<Lottos/>
</>
)
}
export default App;
|
index.js 파일을 만듭니다.
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.querySelector("#app"));
root.render(
<React.StrictMode>
<App/>
</React.StrictMode>
);
|
실행 결과 화면 입니다.



'Front End > React' 카테고리의 다른 글
| [React Exam 40] React Hook 알아보기 (0) | 2024.11.06 |
|---|---|
| [React Exam 39] 가위바위보 게임 만들기 (1) | 2024.11.05 |
| [React Exam 37] 로또 번호 자동 생성기 만들기 (0) | 2024.11.04 |
| [React Exam 36] 시계 만들어보기 (5) | 2024.11.04 |
| [React Exam 35] Counter 만들어보기 (1) | 2024.11.04 |