[리액트 기초반] 2주차 Quiz - 버킷리스트에 아이템을 추가해보자

변시윤·2021년 11월 24일
0

지금까지 배운 내용을 토대로 2주차 - Ref에서 만든 버킷리스트에 input과 추가 버튼을 만든 후, input에 내용을 입력하면 버킷리스트에 새로운 div가 추가되도록 만들어보자.

정답

import React from "react";
import MovieList from "./MovieList";
import styled from "styled-components";

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

    this.state = {
      list: ["Last Night in Soho", "Don't Look Up", "Titane", "Spider-Man: No Way Home"],
    };

    this.text = React.createRef();
  }

  componentDidMount() {  
  }

  addMovie = () => {
    console.log(this.state.list);
    const newMovie = this.text.current.value;
    this.setState({list: [...this.state.list, newMovie]});
  }

  render() {
    
    return (
      <AppWrap>
        <Container>
          <Title>Winter is coming...</Title>
          <Line />
          <MovieList list={this.state.list} />
        </Container>

        <InputWrap>
          <input type="text" ref={this.text}
           onChange={() => {
            console.log(this.text.current.value);
          }}/>
          <button onClick={this.addMovie}>add</button>
        </InputWrap>
      </AppWrap>
    );
  }
}

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

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: 20px auto;
height: 20px;
padding: 16px;
border: 1px solid #ddd;
border-radius: 5px;
display: block;
`;

export default App;

처리 순서

<button> 생성

<InputWrap> 스타일 컴포넌트 생성 후 <input> <button> 묶기

<AppWrap> 스타일 컴포넌트 생성 후 <div className="App"> <AppWrap>로 변환
기존에 있던 import "./style.css";는 주석처리 하거나 제거한다.

<input> onChange 함수로console.log(this.text.current.value); 확인
value가 제대로 들어오나 확인하기 위한 것이므로 필수로 입력할 필요는 없다. 들어오는 것을 확인한 후에 주석처리 해줘도 OK.

addMovie 함수 추가
기존 list<input>의 value를 추가해주면 되는데 객체에 있는 요소를 모두 꺼내줘야 하므로 Spread 연산자를 사용한다. 직관적인 코드를 위해 this.text.current.value는 상수로 선언했다.

<button> addMovie 함수 달기

profile
개그우먼(개발을 그은성으로 하는 우먼)

0개의 댓글