- 목록페이지 작성
- REST API로 데이터 삭제, 추가, 업데이트
- 사용자에게 알림 메시지 표시
- 리액트 앱에서 CSV 파일로 데이터 보내기
MUI 데이터 표 컴포넌트 이용하면 페이지 매김, 필터링, 정렬 기능 사용 가능!
우선 백엔드에서 GET 요청을 하면
_embedded.cars 노드에 있음을 확인할 수 있다.
VS Code에서 새폴더(components)를 만들어준다.
앱에 여러 컴포넌트가 있을 때는 컴포넌트용 폴더를 만드는 것이 좋다.
컴포넌트에 Carlist.js 새파일을 만든다.
Carlist.js 파일에 컴포넌트의 기본 코드를 다음과 같이 작성한다.
import React from "react";
function Carlist() {
return <div></div>;
}
export default Carlist;
Carlist.js 에 나머지 내용 작성 완료!
import React, { useEffect, useState } from "react";
function Carlist() {
// REST API에서 가져온 자동차 정보 담을 객체 (비어있는 배열 기본값으로 선언)
const [cars, setCars] = useState([]);
// fetch 실행. fetch는 첫번째 렌더링 후에 한번만 실행된다.
// JSON 응답 데이터에 있는 자동차 데이터는 cars 상태에 저장된다
useEffect(() => {
fetch("http://localhost:8080/api/cars")
.then((response) => response.json())
.then((data) => setCars(data._embedded.cars))
.catch((err) => console.error(err));
}, []);
// map 함수로 자동차 객체를 표 행으로 변환하고 table 요소 추가
return (
<div>
<table>
<tbody>
{cars.map((car, index) => (
<tr key={index}>
<td>{car.brand}</td>
<td>{car.model}</td>
<td>{car.color}</td>
<td>{car.year}</td>
<td>{car.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Carlist;
App.js 에서 Carlist 컴포넌트 가져오고 렌더링 해야함
import 문 추가하고 return 문에 Carlist 컴포넌트 추가
추가된 부분은 import Carlist from "./components/Carlist"; <Carlist />
import logo from "./logo.svg";
import "./App.css";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import Carlist from "./components/Carlist";
function App() {
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<Typography variant="h6">Carshop</Typography>
</Toolbar>
</AppBar>
<Carlist />
</div>
);
}
export default App;
다 됐으면 npm start 명령으로 리액트 앱 시작!!!
서버 URL 주소는 CRUD 기능을 만들 때 여러번 필요하며
백엔드를 로컬 호스트가 아닌 서버에 배포될 때 달라진다.
따라서 상수로 정의하자!!!!
src 폴더 밑에 constants.js 새파일 만들자!
export const SERVER_URL = 'http://localhost:8080/';
그리고 Carlist.js 수정하자
(import 추가하고 fetch 부분 수정)
import React, { useEffect, useState } from "react";
import { SERVER_URL } from "../constants.js";
//fetch에서 가져온 상수를 이용
function Carlist() {
// REST API에서 가져온 자동차 정보 담을 객체 (비어있는 배열 기본값으로 선언)
const [cars, setCars] = useState([]);
// fetch 실행. fetch는 첫번째 렌더링 후에 한번만 실행된다.
// JSON 응답 데이터에 있는 자동차 데이터는 cars 상태에 저장된다
useEffect(() => {
fetch(SERVER_URL + 'api/cars')
.then((response) => response.json())
.then((data) => setCars(data._embedded.cars))
.catch((err) => console.error(err));
}, []);
// map 함수로 자동차 객체를 표 행으로 변환하고 table 요소 추가
return (
<div>
<table>
<tbody>
{cars.map((car, index) => (
<tr key={index}>
<td>{car.brand}</td>
<td>{car.model}</td>
<td>{car.color}</td>
<td>{car.year}</td>
<td>{car.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Carlist;
MUI 데이터 표 컴포넌트 이용하기
1. 터미널에서 Ctrl + C 눌러서 개발 서버 중지 후 MUI 데이터 표 커뮤니티 버전 설치
npm install @mui/x-data-grid
2. Carlist.js에 import
import { DataGrid } from "@mui/x-data-grid";
3. 데이터 표의 열 정의하기
const columns = [
{field:'brand', headerNmae: 'Brand', width: 200},
{field:'model', headerNmae: 'Model', width: 200},
{field:'color', headerNmae: 'Color', width: 200},
{field:'year', headerNmae: 'Year', width: 150},
{field:'price', headerNmae: 'Price', width: 150},
];
4. return문에도 DataGrid 컴포넌트 추가
return (
<div style={{height:500, width:'100%'}}>
<DataGrid
rows={cars}
columns={columns}
getRowId={row => row._links.self.href}/>
</div>
);
5. 정렬, 필터링, 페이지 매김 가능!!!!!!!!!