this / Big O notation / linked list
Reactλ‘ to do list λ§λ€κΈ°
this / Big O notation / linked list κ³Όμ λ private ν΄λ μ°Έκ³
inputμ value κ°μ μΈλΆμμ μ¬μ©ν μ μλλ‘ todo stateμ λ΄μλ€.
import { useState } from "react";
function App() {
const [todo, setTodo] = useState("");
const onChange = (event) => setTodo(event.target.value);
return (
<div>
<h1>ν μΌ λͺ©λ‘</h1>
<form>
<input
value={todo}
onChange={onChange}
placeholder="ν μΌ μμ±"
autoFocus
/>
</form>
</div>
);
}
export default App;
form μμ μμ submit buttonμ μΆκ°νκ³ form νκ·Έμ onSubmit μ΄λ²€νΈλ₯Ό λ±λ‘νλ€.
submit buttonμ ν΄λ¦ν΄ μ μΆν todoλ₯Ό νλ©΄μ μ
λ°μ΄νΈνκΈ° μν΄ todos stateλ₯Ό μΆκ°νλ€.
import { useState } from "react";
function App() {
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const onChange = (event) => setTodo(event.target.value);
const onSubmit = (event) => {
event.preventDefault();
if (todo === "") return;
setTodos((prevTodos) => [todo, ...prevTodos]); // = μ΄μ todos λ°°μ΄μ νμ¬ todoλ₯Ό unshift νλ€
setTodo("");
};
return (
<div>
<h1>ν μΌ λͺ©λ‘({todos.length})</h1>
<form onSubmit={onSubmit}>
// μ€λ΅
<button type="submit">μΆκ°</button>
</form>
</div>
);
}
export default App;
submit buttonμ ν΄λ¦νμ¬ todos λ°°μ΄μ νμ¬ todoκ° μΆκ°λμ΄ todos stateκ° λ³νλ©΄ App μ»΄ν¬λνΈκ° 리λ λλ§ λλ€.
μ΄λ₯Ό μ΄μ©ν΄ μ 체 ν μΌ λͺ©λ‘μ νλ©΄μ μ
λ°μ΄νΈ ν μ μλ€.
νμ¬ todosμ λ°°μ΄ μμλ todoλ€, μ¦ textλ€μ΄ itemμΌλ‘ λ€μ΄ μλ€.
νλ©΄μ μ΄λ₯Ό 보μ¬μ£ΌκΈ° μν΄μλ κ·Έ itemλ€μ li νκ·Έ μμ μ§μ΄λ£μ ν μ΄λ₯Ό λ λλ§ν΄μΌ νλ€.
todos stateκ° λ³ν λλ§λ€(App μ»΄ν¬λνΈκ° 리λ λλ§ λ λλ§λ€) {μλ°μ€ν¬λ¦½νΈ μ½λ} μμ map()μ μν΄ ν μΌ λͺ©λ‘ μ 체λ 리λ λλ§ λλ€.
map()
μ μλ λ°°μ΄μ λ³νν μλ‘μ΄ λ°°μ΄μ return νκΈ° λλ¬Έμ μ΄λ₯Ό μ΄μ©νλ©΄ todos λ°°μ΄μ item(text)λ₯Ό li μμλ‘ λ°κΏ μ μλ€.
π‘ Warning: Each child in a list should have a unique "key" prop.
Reactκ° κΈ°λ³Έμ μΌλ‘ listμ μλ λͺ¨λ itemμ μΈμνκΈ° λλ¬Έμ
listμ κ°κ°μ itemμ λν΄μλ κ³ μ ν key μμ±μ λΆμ¬ν΄μΌ νλ€.
// μ΅μ’
μμ±
import { useState } from "react";
function App() {
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const onChange = (event) => setTodo(event.target.value);
const onSubmit = (event) => {
event.preventDefault();
if (todo === "") return;
setTodos((prevTodos) => [todo, ...prevTodos]);
setTodo("");
};
return (
<div>
<h1>ν μΌ λͺ©λ‘({todos.length})</h1>
<form onSubmit={onSubmit}>
<input
value={todo}
onChange={onChange}
placeholder="ν μΌ μμ±"
autoFocus
/>
<button type="submit">μΆκ°</button>
</form>
<hr />
<ul> // listμ κ°κ°μ itemμ λν΄ key μμ±μ λΆμ¬ν΄μΌ νλ€
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
}
export default App;