dataEdit.js
import { useRef, useState } from 'react';
const EditList = ({Update}) =>{
const [todo, setTodo] = useState('')
const saveList = useRef()
const submit = (e) =>{
setTodo(e.target.value)
}
const save = (e) =>{
if(todo.length<1){
alert("1글자 이상 입력해주세용!")
return;
}
Update(todo)
setTodo('')
saveList.current.focus();
}
return (
<>
<div className="wrtie_part">
<h2>to do list</h2>
<input ref={saveList} type="text" value={todo} onChange={submit}></input>
<button type="submit" onClick={save}>저장하기</button>
</div>
<div className='body'>
<div>
<p>{todo}</p>
</div>
</div>
</>
)
}
export default EditList;
App.js
function App() {
const [data, setData] = useState([])
const dataId = useRef(1)
const Update= (text,id) => {
const newItem = {text,id:dataId.current}
dataId.current++
setData([...data, newItem])
}
const onDelete = (targetId) =>{
console.log(`${targetId}가 삭제되었다!`)
const newDataList = data.filter((it)=> it.id !== targetId)
setData(newDataList)
}
return (
<div className="App">
<header className="App-header">
<EditList Update={Update}/>
<DataList onDelete={onDelete} data = {data}/>
</header>
</div>
);
}
export default App;
- App.js에서 만든 함수를 dataEdit 컴포넌트에 값을 넘겨서 사용하였다.
dataList.js
import DataItem from "./dataItem"
const DataList = ({finish, onDelete, data})=>{
return (
<div className="hi_data">
<p>할 일 목록!</p>
<div>{data.map((it)=>{
return (
<DataItem key={it.id} {...it} onDelete={onDelete} finish={finish}/>
)})}
</div>
</div>
)
}
export default DataList
- 입력받은 데이터를 dataList.js를 통해 화면에 보여준다.