본문 바로가기

Front End/React

[React Exam 38] 로또 번호 자동 생성기 만들기 2

원하는 게임수를 입력하고 버튼을 클릭하면 지정 게임수 만큼 로또 번호를 출력하는 애플리케이션을 만들어 보겠습니다.

 

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>
);    

 

실행 결과 화면 입니다.