import React from 'react';
import { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import reportWebVitals from './reportWebVitals';
function App(){
const [text, setText] = useState("")
const [todos, setTodos] = useState([])
const onSubmit = (event) => {
event.preventDefault();
if ( text === "" ){
return;
};
setTodos((currentArray) => [...currentArray, text]);
setText("");
}
const onChange = (event) => {
setText(event.target.value)
}
return(
<div>
<h1>My ToDo List {todos.length}</h1>
<form onSubmit={onSubmit}>
<input
value = {text}
type="text"
placeholder="Write To Do"
onChange={onChange}></input>
<button >ADD</button>
</form>
<ul>
{todos.map(( items, index )=> <li key={index}> {items} </li>)}
</ul>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />)
reportWebVitals();
return(
<div>
<h1>My ToDo List {todos.length}</h1>
<form onSubmit={onSubmit}>
<input
value = {text}
type="text"
placeholder="Write To Do"
onChange={onChange}></input>
<button >ADD</button>
</form>
<ul>
{todos.map(( items, index )=> <li key={index}> {items} </li>)}
</ul>
</div>
)
- form내의 submit 기능을 사용하기 위해 form 태그로 감싸주었다
- input에 값을 변수로 넣어주었고, onChange 함수로 변경시 실행할 함수를 지정해주었다.
function App(){
const [text, setText] = useState("")
const [todos, setTodos] = useState([])
const onSubmit = (event) => {
event.preventDefault();
if ( text === "" ){
return;
};
setTodos((currentArray) => [...currentArray, text]);
setText("");
}
const onChange = (event) => {
setText(event.target.value)
}
- text, todos상태를 감시하기 위해 useState로 감싸주었다.
- todos는 배열에 할 일 text가 추가되는 모양이 될 것이므로, 초기값을 빈 배열(array)로 설정하였다.
- onSubmit 함수는, submit 함수 실행의 특성 상, 화면이 새로고침 되는데 이를 방지하기 위해 preventDefalut를 걸어주었고,
- 해당 입력창에 값이 없을 경우에는 함수를 return으로 종료시킨다. 만약 그렇지 않다면 setTodos 함수를 통해
- 현재 배열을 그대로 복사한 ( ...currentArray) 배열에 text를 추가시켜 새로운 배열을 만들고 이를 todos에 적용시킨다.
- 그리고 입력창을 비우기 위해 setText("") 함수를 실행시켜준다.
- onChange 함수는, 해당 내용에 변화가 있을 시에 실행하는 코드로,
- input 창에 입력되는 값을 setText 함수를 통해 text를 갱신해준다.
<ul>
{todos.map(( items, index )=> <li key={index}> {items} </li>)}
</ul>
- todos.map 함수를 통해, 해당 배열의 요소를 순환하며 <li>요소<li>형태의 새로운 배열을 만든다.
Array.prototype.map() - JavaScript | MDN
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
developer.mozilla.org
- array와 관련된 함수들은 다음 문서를 참고하면 좋다.
'Front-end > React.Js' 카테고리의 다른 글
[nomad coder] 리액트 기초 7 - 총정리 (0) | 2022.11.26 |
---|---|
[nomad coder] 리액트 기초 5 - API(코인 시세표) (0) | 2022.11.25 |
[nomad coder] 리액트 기초 3 - 번외(Cleanup Function) (0) | 2022.11.24 |
[nomad coder] 리액트 기초 3 (0) | 2022.11.24 |
[nomad coder] 리액트 기초 2 (0) | 2022.11.24 |
댓글