Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- not 의사클래스
- 일반 형제 결합자
- 임베디드
- i 태그
- Live Server
- br 태그
- iframe
- RGB
- html tag i
- iframe 태그
- css
- width속성
- 자식결합자
- html
- reveal in file explorer
- 인접 형제 결합자
- focus 의사클래스
- sup태그
- go live
- html 태그
- 전체 선택자
- 아두이노
- padding 속성
- id 선택자
- height속성
- Checked 의사 클래스
- RGBA
- tag html
- sub태그
- background-color 속성
Archives
- Today
- Total
so woon!
[React] array의 직접적 수정 없이 element를 추가하는 방법 + 간단히 to do list 만들기 본문
ReactJS/개념정리
[React] array의 직접적 수정 없이 element를 추가하는 방법 + 간단히 to do list 만들기
xowoony 2023. 3. 17. 19:03학습일 : 2023. 03. 17
<여러개의 toDo를 받을 수 있는 array 만들기>
먼저 State를 만든다.
기본값은 비어있는 배열이 된다.
const [toDos, setToDos] = useState( [] );
우리는 State를 직접적으로 수정하지 않는다.
toDo = ""
또는
toDos.push
이런식으로 하지 않는다는 말이다.
그 대신 함수를 사용하여 수정하는데,
setToDo("");
이런식으로 사용해야 한다.
전체 코드
import { useState } from "react";
function App() {
// toDo
const [toDo, setToDo] = useState("");
// 여러개의 toDo를 받는 배열 만들기
const [toDos, setToDos] = useState([]);
// onChange
const onChange = (event) => setToDo(event.target.value);
// onSubmit
const onSubmit = (event) => {
event.preventDefault(); // 페이지가 새로고침 되는 것을 방지
if (toDo === "") {
return; // 만약 toDo 값이 비었다면 이 함수를 작동하지 않게함
}
setToDo(""); // toDo 값이 있다면 toDo 즉 input 값을 ""로 비워줌
// toDo 값은 input과 연결되어 있음 , input을 비워준다.
};
console.log(toDos);
return (
<div>
<form onSubmit={onSubmit}>
<input
onChange={onChange}
value={toDo}
type="text"
placeholder="write your to do..."
/>
<button>처음으로</button>
</form>
</div>
);
}
export default App;
다음으로
<array를 직접적으로 수정하지 않으면서 array에 element를 추가하는 방법>
직접적 수정 없이 array에 추가하는 방법은 아래와 같다.
setToDos((currentArray) => [toDo, ...currentArray]);
이런 방식으로 작성해주면 된다!
맨 앞부분에 가장 최근에 작성해준 element 가 추가가 된다.
위에서 학습한 내용을 응용하여
오늘의 계획 관리 사이트를 간단하게
만들어보자.
<App.js>
import { useState } from "react";
function App() {
// toDo
const [toDo, setToDo] = useState("");
// 여러개의 toDo를 받는 배열 만들기
const [toDos, setToDos] = useState([]); // 어플리케이션이 처음 시작될 땐 비어있는 array를 가짐
// onChange
const onChange = (event) => setToDo(event.target.value);
// onSubmit
const onSubmit = (event) => {
event.preventDefault(); // 페이지가 새로고침 되는 것을 방지
if (toDo === "") {
return; // 만약 toDo 값이 비었다면 이 함수를 작동하지 않게함
}
// array를 직접적으로 수정하지 않고 setToDos로 배열에 element 추가하는 법
// currentArray => {} 는 function(currentArray){return ...}와 같다.
//currentArray는 현재의 state
// ...을 찍으면 currentArray를 불러올 수 있게 된다.
setToDos((currentArray) => [toDo, ...currentArray]);
// toDo 값이 있다면 toDo 즉 input 값을 ""로 비워줌
// toDo 값은 input과 연결되어 있음 , input을 비워준다.
setToDo("");
};
console.log(toDos);
return (
<div style={{alignItems:"center", display:"flex", flexDirection:"column", justifyContent:"center"}}>
<h4 style={{fontSize:"3rem"}}>오늘의 계획</h4>
<h7>오늘의 계획은 총 {toDos.length}개 입니다.</h7>
<form onSubmit={onSubmit}>
<input
onChange={onChange}
value={toDo}
type="text"
placeholder="오늘 해야할 일을 입력해주세요"
style={{
marginTop:"1rem",
width: "20rem",
height: "2rem",
}}
/>
<button
style={{
marginLeft: "0.2rem",
height: "2.3rem",
color: "white",
backgroundColor: "black",
}}
>
추가하기
</button>
<h4 style={{fontSize : "1rem"}}>{toDos + " "}</h4>
</form>
</div>
);
}
export default App;
실행결과
추가된 계획은 몇개인지,
추가한 계획의 내용이 아래에 바로 표시될 수 있게
구성해보았다.
+ 리스트로 만들어보기
<App.js>
import { useState } from "react";
function App() {
// toDo
const [toDo, setToDo] = useState("");
// 여러개의 toDo를 받는 배열 만들기
const [toDos, setToDos] = useState([]); // 어플리케이션이 처음 시작될 땐 비어있는 array를 가짐
// onChange
const onChange = (event) => setToDo(event.target.value);
// onSubmit
const onSubmit = (event) => {
event.preventDefault(); // 페이지가 새로고침 되는 것을 방지
if (toDo === "") {
return; // 만약 toDo 값이 비었다면 이 함수를 작동하지 않게함
}
// array를 직접적으로 수정하지 않고 setToDos로 배열에 element 추가하는 법
// currentArray => {} 는 function(currentArray){return ...}와 같다.
//currentArray는 현재의 state
// ...을 찍으면 currentArray를 불러올 수 있게 된다.
setToDos((currentArray) => [toDo, ...currentArray]);
// toDo 값이 있다면 toDo 즉 input 값을 ""로 비워줌
// toDo 값은 input과 연결되어 있음 , input을 비워준다.
setToDo("");
};
console.log(toDos);
return (
<div
style={{
alignItems: "center",
display: "flex",
flexDirection: "column",
justifyContent: "center",
}}
>
<h4 style={{ fontSize: "3rem" }}>오늘의 계획</h4>
<h3>오늘의 계획은 총 {toDos.length}개 입니다.</h3>
<form onSubmit={onSubmit}>
<input
onChange={onChange}
value={toDo}
type="text"
placeholder="오늘 해야할 일을 입력해주세요"
style={{
marginTop: "1rem",
width: "20rem",
height: "2rem",
}}
/>
<button
style={{
marginLeft: "0.2rem",
height: "2.3rem",
color: "white",
backgroundColor: "black",
}}
>
추가하기
</button>
</form>
{/* map() 의 역할은 예전 array를 가져와서 새로운 배열로 변형해준다.
리턴하는게 어떤 값이던지 그 값이 새로운 배열이 된다.*/}
<ul>
{/* map함수는 첫번째는 value, 두번째는 index여야한다. 숫자를 입력해줄경우는 두번째 인자에 index를 넘겨줘야 함.*/}
{toDos.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
export default App;
실행결과
'ReactJS > 개념정리' 카테고리의 다른 글
[React] 코인변환기 만들기 (0) | 2023.03.19 |
---|---|
[React] URL fetch하기 | 코인 정보 불러오기 (0) | 2023.03.18 |
[React] Cleanup function (1) | 2023.03.17 |
[React] 클릭시 요소 표시/숨기기 (0) | 2023.03.17 |
[React] 특정 코드가 변화했을 때만 코드를 실행시키는법 (0) | 2023.03.16 |
Comments