프로그래밍/Weekly I Learned

2023.10.31+ counter,totalcounter react

타코코딩 2023. 11. 2. 10:54
import { useState } from "react";
import "./App.css";
import Counter from "./components/Counter";
import styled from "styled-components";

const TotalBox = styled.div`
  display: flex;
  flex-direction: column;
`;

function App() {
  // 리턴시 반드시 하나의 태그만 출력한다
  const [total, setTotal] = useState(0);

  return (
    <TotalBox className="flex_box">
      <div style={{ textAlign: "center", fontSize: "5rem" }}>
        total : {total}
      </div>
      <Counter setTotal={setTotal} total={total}></Counter>
      <Counter setTotal={setTotal} total={total}></Counter>
      <Counter setTotal={setTotal} total={total}></Counter>
    </TotalBox>
  );
}

export default App;
import React, { useState } from "react";
import styled from "styled-components";

const CountBox = styled.div`
  background: linear-gradient(#e66465, #9198e5);
  margin: 10px auto;
  left: calc(50% - 50px);
  top: calc(50% - 50px);
  display: flex;
  height: 100px;
  width: 100px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px;
`;

const Number = styled.span`
  font-size: 30px;
  transition: all 0.2s linear;
  &:hover {
    transform: rotateX(720deg);
  }
`;
const NButton = styled.button`
  background-color: tomato;
  border-radius: 50%;
  padding: 5px;
  &:active {
    transform: scale(1.5);
  }
`;

const Counter = ({ setTotal, total }) => {
  const [counter, setCounter] = useState(0);

  function increase(a = 1) {
    setCounter((counter) => counter + a);
    setTotal((total) => total + a);
  }

  return (
    <div>
      <CountBox>
        <Number>
          {counter}/{total}
        </Number>
        <NButton
          type="button"
          onClick={() => {
            increase();
          }}>
          Add + 1
        </NButton>
      </CountBox>
    </div>
  );
};

export default Counter;