import { Fragment, useState } from "react";
function App() {
const [title, setTitle] = useState("");
return (
<div className="container">
<div className="mb-3">
<label className="form-label"></label>
<input
className="form-control"
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
/>
</div>
<button className="btn btn-primary">Post</button>
</div>
);
}
export default App;
import { Fragment, useState } from "react";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const onSubmit = () => {
console.log(title, body);
};
return (
<div className="container">
<div className="mb-3">
<label className="form-label">Title</label>
<input
className="form-control"
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
/>
</div>
<div className="mb-3">
<label className="form-label">Body</label>
<textarea
className="form-control"
value={body}
onChange={(e) => {
setBody(e.target.value);
}}
rows="20"
/>
</div>
<button onClick={onSubmit} className="btn btn-primary">
Post
</button>
</div>
);
}
export default App;
post하면 데이터베이스에 저장을 해야 한다.
가짜 db 패키지인 json-server가 있다.
npm install json-server
package.json에 json-server가 들어간다.
db.json 파일을 만든다.
{
"posts":[]
}
다음 명령어로 db를 실행한다.
json-server --watch db.json
npm install axios
https://poiemaweb.com/json-server
JSON Server | PoiemaWeb
json-server는 json 파일을 사용하여 간단한 시뮬레이션을 위한 REST API Mock server를 구축할 수 있는 툴이다.
poiemaweb.com
3000포트로 보낼 때 데이터 값과 함께 보내게 되고, DB에 저장하게 된다.
키와 값의 명이 동일할 경우 생략 가능하다.
import { Fragment, useState } from "react";
import axios from "axios";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const onSubmit = () => {
axios.post('http://localhost:3000/posts', {
title: title,
body: body
})
console.log(title, body);
};
import { Fragment, useState } from "react";
import axios from "axios";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const onSubmit = () => {
axios.post('http://localhost:3000/posts', {
title,
body
})
console.log(title, body);
};
리액트 프로젝트가 3000 포트이므로 db 종료 후 3001 포트로 바꿔준다.
npm run db
해야 db가 실행된다.
[리액트] 컴포넌트, 함수, Fragment, 이벤트, useState, Bootstrap (0) | 2023.10.12 |
---|---|
[리액트] 구구단 만들기 (0) | 2023.10.05 |
[리액트를 다루는 기술 1~2장] 요약 정리+스터디 문제 (0) | 2023.09.20 |