관리 메뉴

Life goes slowly...

ag-Grid-React Row 편집 본문

프로그래밍/React.js

ag-Grid-React Row 편집

빨강소 2025. 5. 18. 07:29
728x90
반응형

 

 

 

ag-grid-react에서 행(row) 편집 기능은 매우 강력하며, 인라인(in-place) 방식으로 데이터를 편집할 수 있습니다. React 개발자의 관점에서 보면, 셀 편집은 자동으로 관리되지만, 외부 상태 동기화나 저장 버튼과의 연동을 직접 제어할 수 있어야 실전에서 유용합니다.


✅ 기본 행 편집 방식

Ag-Grid는 셀 단위 편집을 지원하지만, 그리드 옵션을 조금만 설정하면 **행 단위 편집(row editing)**처럼 동작하게 할 수 있습니다.

 

import React, { useState } from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-alpine.css";

const RowDataEidt = () => {
  const [rowData, setRowData] = useState([
    { make: "Hyundai", model: "Sonata", price: 2500 },
    { make: "Kia", model: "K5", price: 2700 },
  ]);

  const [columnDefs] = useState([
    { field: "make", editable: true },
    { field: "model", editable: true },
    { field: "price", editable: true },
  ]);
  
  //저장 버튼과 연동
  const handleSave = () => {
  	const updatedData = [];
    gridRef.current.api.forEachNode((node) => {
    	updatedData.push(node.data);
     });
     console.log("저장할 데이터:", updatedData);
     // → 서버로 전송
  };

  return (
    <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
      <AgGridReact
        rowData={rowData}
        columnDefs={columnDefs}
        onCellValueChanged={(params) => {
        	console.log("변경된 행 데이터:", params.data);
            // 저장 API 호출하거나 로컬 상태 반영
        }}
        defaultColDef={{
          resizable: true,
          sortable: true,
        }}
      />
    </div>
  );
};

* editable: true를 설정한 컬럼은 기본적으로 더블 클릭하면 편집 가능해집니다.

728x90
반응형
Comments