Ming's develop story

Chapter3 - 버킷리스트에 아이템 추가하기! 본문

스파르타코딩클럽 - 항해99/항해99 Chapter3 - react 주특기 기본

Chapter3 - 버킷리스트에 아이템 추가하기!

Ming 2021. 11. 18. 00:37

App.js

원래 작성했던 버킷리스트 코드에 '추가하기'라는 버튼을 추가해주고,

addBucket 함수 추가 및 css 수정

import React from "react";
import BucketList from "./BucketList";
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);
    const new_item = this.text.current.value;
    // ... 스프레드 문법은 [1, ,2, 3] 또는 {a : b}
    // 처럼 배열이나 딕셔너리 안의 요소를 밖으로 다 꺼내준다.
    // [...this.state.list, 넣고 싶었던 어떤 값]
    this.setState({ list: [...this.state.list, new_item] });
  };

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

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

const Appwrap = styled.div`
  .App {
    background-color: #eee;
    height: 100vh; /*vh는 화면을 기준으로 높이를 얼마나 줄지 정할 수 있다. */
    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 InputWrap = styled.div`
  background-color: #fff;
  width: 50vw;
  max-width: 350px;
  margin: auto;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 5px;
`;

export default App;

여기서 스프레드 문법 ... 을 잘 활용해야 하는데 

... 은 배열이나 딕셔너리 안의 요소를 밖으로 다 꺼내주는 역할을 한다.

여기서는 []로 감싸주면서 저 요소로 새로운 배열을 생성하는식으로 사용했다.

 

BucketList.js - 그대로

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

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

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;

 

 

결과물 

 

Comments