728x90
참고자료: 유튜브 생활코딩 React 2022 개정판 https://www.youtube.com/playlist?list=PLuHgQVnccGMCOGstdDZvH41x0Vtvwyxu7
1. 목록을 crate해보자!
Create 버튼 만들기
function App() {
...중략...
return (
<div>
...중략...
<a href='/create' onClick={event=>{
event.preventDefault();
setMode("CREATE");
}}>Create</a>
</div>
);
}
👉🏻App의 return 부분에 a tag로 Create 버튼을 만들어준다. onClick 이벤트에 a tag의 기능을 막아주고 mode state를 CREATE로 변경해준다.
Nav에 리스트 CREATE 하기
function Create(props) {
return (
<article>
<h2>Create</h2>
<form onSubmit={event=>{
event.preventDefault();
const title = event.target.title.value;
const body = event.target.body.value;
props.onCreate(title, body);
}}>
<p><input type="text" name="title" placeholder="title"></input></p>
<p><textarea name="body" placeholder='body'></textarea></p>
<p><input type="submit" value="Create"></input></p>
</form>
</article>
)
}
👉🏻Create 컴포넌트는 이와 같다.
function App() {
const [mode, setMode] = useState("WELCOME");
const [id, setId] = useState(null);
const [nextId, setNextId] = useState(4);
const [topics, setTopics] = useState([
{id : 1, title : 'html', body : 'html is ...'},
{id : 2, title : 'css', body : 'css is ...'},
{id : 3, title : 'js', body : 'js is ...'},
]);
let content = null;
if (mode === "WELCOME") {...}
else if (mode === "READ") {...}
else if (mode === "CREATE") {
content = <Create onCreate={(_title, _body)=>{
const newTopic = {id: nextId, title: _title, body: _body}
const newTopics = [...topics]
newTopics.push(newTopic);
setTopics(newTopics);
setMode("READ");
setId(nextId);
setNextId(nextId + 1);
}}></Create>
}
return (...중략...);
}
- topics 리스트를 ustState를 활용해 state로 만든다. 그리고 nextId라는 state를 만든다.
- form에서 받은 정보로 newTopic이라는 객체를 만든다.
- topics를 복제한 newTopics에 newTopic 객체를 추가하고 setTopics로 state를 갱신한다.
- mode를 READ로 id를 nextId로 설정해서 글을 create하면 글을 생성하는 동시에 방금 생성한 글이 나오게 한다.
- 마지막으로 nextId에 1을 더해 현재 Nav의 마지막 Id값을 갱신한다.
✍🏻[...topics]: topics라는 리스트를 복제한다.
728x90
'그 땐 Front했지 > 그 땐 React했지' 카테고리의 다른 글
[생활코딩/React] 2022개정판 | 10. delete (0) | 2022.05.06 |
---|---|
[생활코딩/React] 2022개정판 | 9. update (0) | 2022.05.06 |
[생활코딩/React] 2022개정판 | 7. state (0) | 2022.05.05 |
[생활코딩/React] 2022개정판 | 6. 이벤트 (0) | 2022.05.02 |
[생활코딩/React] 2022개정판 | 4. 컴포넌트 만들기 (0) | 2022.05.02 |