상세 컨텐츠

본문 제목

[리액트] 블로그 포스트 생성 폼 만들기

리액트 스터디

by front-hyun 2023. 10. 12. 15:11

본문

Input State 바인딩

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;

Textarea State 바인딩

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;

 

 

json-server 설치

post하면 데이터베이스에 저장을 해야 한다. 

가짜 db 패키지인 json-server가 있다. 

npm install json-server

package.json에 json-server가 들어간다. 

db.json 파일을 만든다. 

{
    "posts":[]
}

 

다음 명령어로 db를 실행한다. 

json-server --watch db.json

 

DB에 데이터 저장

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가 실행된다. 

관련글 더보기