<์ ์ฒด ์ฝ๋>
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js
import React, { 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((currentArray)=>[toDo,...currentArray])
setToDo("")
}
return(
<div>
<h1>My To Dos ({toDos.length})</h1>
<form onSubmit={onSubmit}>
<input onChange={onChange} value={toDo} type="text" placeholder='write your to do...'/>
<button>Add To Do</button>
</form>
<hr/>
<ul>
{toDos.map((item,index)=>(
<li key={index}>{item}</li>
))}
</ul>
</div>
)
}
export default App;
+Plus
1.
const onSubmit = (event)=>{
event.preventDefault()
if(toDo===""){
return
}
setToDos((currentArray)=>[toDo,...currentArray])
setToDo("")
}
์ ์ถ ๋ฒํผ์ ๋๋ฅด๊ฒ ๋๋ฉด setToDos function์ ์ํด์ ํ์ฌ ์ ์ฅ๋ array์ toDo๊ฐ ์ถ๊ฐ ๋๋ค!
2.
<ul>
{toDos.map((item,index)=>(
<li key={index}>{item}</li>
))}
</ul>
map()๋ฉ์๋๋ฅผ ํตํด toDos์ ์ ์ฅ๋ ๊ฐ๋ค์ ํ๋์ฉ ๋ถ๋ฌ์ ๋ณด์ฌ์ฃผ๋๋ฐ, item๋ง ๋ถ๋ฌ์ li ํ๊ทธ๋ก item์ ํธ์ถํ๋ฉด ๋ค์๊ณผ ๊ฐ์ ์ค๋ฅ๊ฐ ๋จ๊ฒ ๋๋ค.
map๋ฉ์๋๋ ๊ฐ item๋ง๋ค ๋ ๋ฆฝ์ ์ธ key ๊ฐ์ ๋ถ์ฌํด์ผํ๊ธฐ ๋๋ฌธ! ๋ฐ๋ผ์ li์ key๊ฐ์ผ๋ก map()๋ฉ์๋์ ๋๋ฒ์งธ ์ธ์์ธ index๋ฅผ ๋ณ์๋ก ๋ฐ์์ ๋ฃ์ด์ฃผ๋ฉด ์ค๋ฅ๊ฐ ํด๊ฒฐ๋๋ค.
'Development > React.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ ธ๋ง๋์ฝ๋ React JS ํด๋์ค #3 typescript (0) | 2022.06.29 |
---|---|
๋ ธ๋ง๋์ฝ๋ React JS ํด๋์ค #2 styled components - log (0) | 2022.06.28 |
[nomadcoders_React.js]log3 (0) | 2022.06.21 |
[nomadcoders_React.js]log2 (0) | 2022.06.17 |
[nomadcoders_React.js]log1 (0) | 2022.06.17 |
๋๊ธ