티스토리 뷰

728x90
반응형

개요



React 에서 버튼 이벤트를 통해 데이터를 추가해 보자 !!

배열 리스트의 데이터를 동적으로 추가하여 조회해 보자 !!



컴포넌트 / 구조



React 는 단방향으로만 데이터가 흐르기 때문에 같은 레벨에 있는 컴포넌트 끼리 데이터를 주고 받을 수 있도록, 

공통 부모의 state를 활용한 state 끌어올리기를 통해 데이터를 제어 한다.


Component / Structure


state 끌어올리기를 통해 공통 부모 컴포넌트의 state 는 Event(setData) 는 아래에서 위로, DATA(Data)는 위에서 아래로의 데이터 흐름을 가진다.



App.js



import { useState, useRef } from "react";
import ReportEditor from "./ReportEditor";
import ReportList from "./ReportList";

const App = () => {
  const [data, setData] = useState([]);
  const dataId = useRef(0);

  const onCreate = (author, content, grade) => {
    const newItem = {
      author,
      content,
      grade,
      id: dataId.current
    };
    dataId.current += 1;
    setData([newItem, ...data]);
  };

  return (
    <div className="App">
      <ReportEditor onCreate={onCreate} />	//onCreate 메소드 전달
      <ReportList reportList={data} />	//data State 전달
    </div>
  );
};
export default App;

 

ReportEditor.js 와 ReportList.js 의 공통 컴포넌트인 App.js 에서 data State를 사용하여 ReportEditor.js 에서 추가하는 보고서 를 ReportList.js 에서 보여질 수 있도록 한다. (State 끌어올리기)

보고서를 추가해야 하는 ReportEditor.js 에는 data State를 변경하는 onCreate 메소드를 prop 으로 전달하고,
보고서 리스트를 보여주는 ReportList.js 에는 data State 를 prop 으로 전달한다.



ReportEditor.js



import { useState, useRef } from "react";

const ReportEditor = ({ onCreate }) => {
  const authorInput = useRef();
  const contentInput = useRef();

  const [state, setState] = useState({
    author: "",
    content: "",
    grade: 1
  });

  const handleChangeState = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = () => {
    if (state.author.length < 1) {
      authorInput.current.focus();
      return;
    }

    if (state.content.length < 5) {
      contentInput.current.focus();
      return;
    }
    onCreate(state.author, state.content, state.grade);
    alert("저장 성공");
    setState({
      author: "",
      content: "",
      grade: 1
    });
  };

  return (
    <div className="ReportEditor">
      <h2>오늘의 보고</h2>
      <div>
        작성자
        <input
          ref={authorInput}
          value={state.author}
          onChange={handleChangeState}
          name="author"
        />
      </div>
      <div>
        <textarea
          ref={contentInput}
          value={state.content}
          onChange={handleChangeState}
          name="content"
          type="text"
        />
      </div>

      <div>
        <span>오늘의 평가점수 : </span>
        <select name="grade" value={state.grade} onChange={handleChangeState}>
          <option value={1}>1</option>
          <option value={2}>2</option>
          <option value={3}>3</option>
          <option value={4}>4</option>
          <option value={5}>5</option>
        </select>
      </div>
      <div>
        <button onClick={handleSubmit}>보고 저장하기</button>
      </div>
    </div>
  );
};
export default ReportEditor;

App.js 에서 prop 으로 onCreate 메소드를 전달 받아, 새로운 보고서를 작성하고 저장 버튼을 누르게 되면, handleSubmit 메소드에서 onCreate 메소드를 호출 시켜, App.js 의 data State의 값(배열)을 추가 한다.

 

 

ReportList.js



import ReportItem from "./ReportItem";

const ReportList = ({ reportList }) => {
  return (
    <div>
      <h2>보고 리스트</h2>
      {reportList.length}개의 보고가 있습니다.
      <div>
        {reportList.map((it) => {
          return <ReportItem key={it.id} {...it} />;
        })}
      </div>
    </div>
  );
};

export default ReportList;

App.js 에서 prop 으로 data State를 전달 받았기 때문에, ReportEditor.js 에서 보고서를 추가하여 data State가 변경되게 되면 자동으로 ReportList.js 가 re-rendering 되어 추가된 보고서 리스트를 보여주게 된다.



참고



https://espania.tistory.com/356
 

[React] 실습 / 리스트 조회(rendering)

개요 부모 태그에서 전달받은 데이터를 리스트 형태로 출력 해보자. App.js(부모 태그) import "./App.css"; import ReportList from "./ReportList"; const App = () => { const dummyList = [ { id: 1, author:..

espania.tistory.com

https://espania.tistory.com/354?category=1008523

 

[React] 실습 / 사용자 입력 처리

한 줄 입력 처리 React 에서 state를 활용하여 input 태그의 value 값을 초기화 해주거나 변경 해 줄 수 있다. import { useState } from "react"; const ReportEditor = () => { const [author, setAuthor] = use..

espania.tistory.com

https://codesandbox.io/s/icy-dew-cyq61t?file=/src/ReportList.js 

 

icy-dew-cyq61t - CodeSandbox

icy-dew-cyq61t by jins4731 using react, react-dom, react-scripts

codesandbox.io



728x90
댓글
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2026/01   »
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 31
글 보관함