본문 바로가기

study_IT/기타

React 에서 생성(Create) 기능 구현하기

728x90
반응형

React에서 생성(Create) 기능을 구현하는 방법은 다양하며, 주로 상태(state)를 활용하여 새로운 데이터를 관리하고 UI를 업데이트합니다. 아래의 코드 예제는 React 함수형 컴포넌트에서 생성(Create) 기능을 구현하는 방법을 보여줍니다.

import { useState } from 'react';

function Article(props) {
  return (
    <article>
      <h2>{props.title}</h2>
      {props.body}
    </article>
  );
}

function Header(props) {
  return (
    <header>
      <h1>
        <a href="/" onClick={(event) => {
          event.preventDefault();
          props.onChangeMode();
        }}>{props.title}</a>
      </h1>
    </header>
  );
}

function Nav(props) {
  const lis = [];
  for (let i = 0; i < props.topics.length; i++) {
    let t = props.topics[i];
    lis.push(
      <li key={t.id}>
        <a
          id={t.id}
          href={'/read/' + t.id}
          onClick={(event) => {
            event.preventDefault();
            props.onChangeMode(Number(event.target.id));
          }}
        >
          {t.title}
        </a>
      </li>
    );
  }
  return (
    <nav>
      <ol>{lis}</ol>
    </nav>
  );
}

function Create(props) {
  return (
    <article>
      <h2>Create</h2>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const title = event.target.title.value;
          const body = event.target.body.value;
          props.onCreate(title, body);
        }}
      >
        <p><input type="text" name="title" placeholder="title" /></p>
        <p><textarea name="body" placeholder="body"></textarea></p>
        <p><input type="submit" value="Create"></input></p>
      </form>
    </article>
  );
}

function App() {
  const [mode, setMode] = useState('WELCOME');
  const [id, setId] = useState(null);
  const [nextId, setNextId] = useState(4);
  const [topics, setTopics] = useState([
    { id: 1, title: 'html', body: 'html is ...' },
    { id: 2, title: 'css', body: 'css is ...' },
    { id: 3, title: 'javascript', body: 'javascript is ...' }
  ]);
  let content = null;

  if (mode === 'WELCOME') {
    content = <Article title="Welcome" body="Hello, WEB"></Article>;
  } else if (mode === 'READ') {
    let title, body = null;
    for (let i = 0; i < topics.length; i++) {
      if (topics[i].id === id) {
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    content = <Article title={title} body={body}></Article>;
  } else if (mode === 'CREATE') {
    content = <Create onCreate={(_title, _body) => {
      const newTopic = { id: nextId, title: _title, body: _body }
      const newTopics = [...topics]
      newTopics.push(newTopic);
      setTopics(newTopics);
      setMode('READ');
      setId(nextId);
      setNextId(nextId + 1);
    }}></Create>;
  }

  return (
    <div>
      <Header title="WEB" onChangeMode={() => {
        setMode('WELCOME');
      }}></Header>
      <Nav topics={topics} onChangeMode={(_id) => {
        setMode('READ');
        setId(_id);
      }}></Nav>
      {content}
      <a href="/create" onClick={(event) => {
        event.preventDefault();
        setMode('CREATE');
      }}>Create</a>
    </div>
  );
}

export default App;

 

위의 코드에서 주요 포인트는 다음과 같습니다.

1. `useState` 훅을 사용하여 상태를 관리합니다. `topics` 배열은 생성(Create)할 데이터를 저장하고, `nextId`는 새로운 데이터의 고유 ID를 관리합니다.

2. "Create" 링크를 클릭하면 `setMode('CREATE')`을 호출하여 모드를 "CREATE"로 변경하고, `Create` 컴포넌트가 렌더링됩니다.

3. `Create` 컴포넌트에서 제출(submit) 버튼을 누르면 `onCreate` 함수가 호출되어 새로운 데이터를 생성하고 `topics` 배열에 추가합니다.

4. `topics` 배열의 변경을 `setTopics`로 반영하여 UI를 업데이트합니다.

5. 생성된 데이터는 `Read` 모드로 전환되어 해당 데이터를 확인할 수 있습니다.

 

참고영상 : https://opentutorials.org/course/4900/31269

728x90
반응형