[React] 투두리스트: 고유한 아이디 라이브러리

조수진·2023년 7월 15일

npm install uuid
import { v4 as uuidv4 } from 'uuid'
uuidv4();


//AddTodo.jsx

import React, { useState } from 'react'
import { v4 as uuidv4 } from 'uuid'

export default function AddTodo ({ onAdd }) {
  const [text, setText] = useState('')
  const handleChange = (e) => {
    setText(e.target.value)
  }

  const handleSubmit = (e) => {
    e.preventDefault()    //페이지 리프레쉬 되지 않도록
    if(text.trim() === '') {     //trim은 여백을 모두 없애주는 메서드 
      return
    } else {
      onAdd({ id: uuidv4(), text, status: 'active' })
      setText('')
    }
  }

  return (
    <div>
      <form onSubmit={ handleSubmit }>
        <input type='text' placeholder='Add Todo' value={ text } onChange={ handleChange } />
        <button>Add</button>
      </form>
    </div >
  )
}
profile
꾸준함의 힘을 믿는 프론트엔드 개발자

0개의 댓글