2021년 4월 6일(React - ToDoList)

Ji Taek Lim·2021년 4월 6일
1
post-thumbnail

todo list를 만들어 본다.

목업을 만들고 function을 구현해보려고 하는데 post기능을 구현하기가 어렵다.

페어님과 이렇게 짜보려고 한다.


App.js

/*
In the previous iteration of this todo list app, we pulled in todos data from a JSON file and mapped over it to display the todo items.

Eventually we'll want to be able to modify the data, which will only happen if we've "loaded" the data in to the component's state

Challenge: Change the <App /> component into a stateful class component and load the imported `todosData` into state.
*/

import React from "react";
import TodoItem from "./TodoItem";
import todosData from "./todosData";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: todosData,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    // Update state so that the item with the given id flips `completed` from false to true (or vise versa)
    // Remember not to modify prevState directly, but instead to return a new version of state with
    // the change you want included in that update.
    // (Think how you might use the `.map` method to do this)
    this.setState((prevState) => {
      const updatedTodos = prevState.todos.map((todo) => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      });
      console.log(prevState.todos);
      console.log(updatedTodos);
      return {
        todos: updatedTodos,
      };
    });
  }

  render() {
    const todoItems = todosData.map((item) => (
      <TodoItem key={item.id} item={item} handleChange={this.handleChange} />
    ));
    return <div className="todo-list">{todoItems}</div>;
  }
}

export default App;

TodoItem

/**
 * Challenge: Style the completed todo items differently from the incomplete items.
 */

import React from "react";

function TodoItem(props) {
  const completedStyle = {
    fontStyle: "italic",
    color: "#cdcdcd",
    textDecoration: "line-through",
  };
  return (
    <div className="todo-item">
      <input
        type="checkbox"
        checked={props.item.completed}
        onChange={() => props.handleChange(props.item.id)}
      />
      <p style={props.item.completed ? completedStyle : null}>
        {props.item.text}
      </p>
    </div>
  );
}

export default TodoItem;

https://www.youtube.com/watch?v=nUl5QLkVdvU&t=309s

profile
임지택입니다.

0개의 댓글