리액트(React)

(리액트)버킷리스트에 항목 하나씩 채우기

changy0ng 2022. 7. 25. 18:29

버킷리스트
1. 가장 먼저 뷰를 만들고 (텍스트를 입력하는 input), 입력한거를 추가하기 위한 버튼(이거 먼저 만들기)
2. Ref를 가지고서 이 input을 가지고 오는거
3. input에서 "text"를 가져와야 하는데 추가하기 버튼 눌렀을 때 가지고 와야함
4. App.js에 App 컴포넌트 State에 그 텍스트를 추가하면 됨

 

목표는 이렇게 하나씩 리스트가 붙게 만드는것이며 style.css를 사용하지 않고 css 스타일링은 모두 styled-components를 활용한다.

 

//App.js

import React from "react";
import BucketList from "./BucketList";
//import "./style.css";
import styled from "styled-components";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      list: ["영화관 가기", "매일 책읽기", "수영 배우기"],
    };

    this.text = React.createRef();
  }

  componentDidMount() {}

  addBucket = () => {
    //console.log(this.text.current.value);   이것으로 input넣은거 잘 넘어왔는지 console에서 확인하기
    //[...this.state.list, 넣고 싶었던 어떤 값]인데 여기서 list를 
    //spread문법으로 꺼내서 가져왔기에 []으로 다시 가두기
    this.setState({ list: [...this.state.list, this.text.current.value] });
  };

  render() {
    return (
      <AppWrap>
        <Container>
          <Title>내 버킷리스트</Title>
          <Line />
          <BucketList list={this.state.list} />
        </Container>

        <Input>
          <input type="text" ref={this.text} />
          <button onClick={this.addBucket}>추가하기</button>
        </Input>
      </AppWrap>
    );
  }
}

const AppWrap = styled.div`
  background-color: #eee;
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
`;

const Container = styled.div`
  background-color: #fff;
  width: 50vw;
  max-width: 350px;
  margin: auto;
  height: 80vh;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 5px;
`;

const Title = styled.h1`
  color: slateblue;
  text-align: center;
`;

const Line = styled.hr`
  margin: 16px 0px;
`;

const Input = styled.div`
  background-color: #fff;
  width: 50vw;
  max-width: 350px;
  margin: 20px auto;
  height: 10vh;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 5px;
`;

export default App;

그리고 BucketList.js

//BucketList.js

import React from "react";
import styled from "styled-components";

const BucketList = ({ list }) => {
  const my_lists = list;
  const my_wrap = React.useRef(null);

//   const [count, setCount] = React.useState(1);
//   const input_count = Array.from({ length: count}, (v, i) => i);

  return (
    <div ref={my_wrap}>
      {my_lists.map((list, index) => {
        return <ItemStyle key={index}>{list}</ItemStyle>;
      })}
    </div>
  );
};

const ItemStyle = styled.div`
  padding: 16px;
  margin: 8px;
  background-color: aliceblue;
`;

export default BucketList;