こちらのプログラムを改造して、連想配列を表示します。
React: JSON をテーブルで表示
次の JSON を CORS のヘッダーがある形で受信します。
Access-Control-Allow-Origin: *
cities.json
{
"t0921": { "name": "宇都宮", "population": 41295, "date_mod": "2003-8-12" },
"t0922": { "name": "小山", "population": 38756, "date_mod": "2003-5-15" },
"t0923": { "name": "佐野", "population": 71294, "date_mod": "2003-6-8" },
"t0924": { "name": "足利", "population": 27138, "date_mod": "2003-7-21" },
"t0925": { "name": "日光", "population": 74682, "date_mod": "2003-4-19" },
"t0926": { "name": "下野", "population": 82951, "date_mod": "2003-10-14" },
"t0927": { "name": "さくら", "population": 96823, "date_mod": "2003-5-24" },
"t0928": { "name": "矢板", "population": 57926, "date_mod": "2003-2-12" },
"t0929": { "name": "真岡", "population": 64187, "date_mod": "2003-11-14" },
"t0930": { "name": "栃木", "population": 82354, "date_mod": "2003-7-04" },
"t0931": { "name": "大田原", "population": 72681, "date_mod": "2003-9-17" },
"t0932": { "name": "鹿沼", "population": 23749, "date_mod": "2003-7-20" },
"t0933": { "name": "那須塩原", "population": 12759, "date_mod": "2003-3-12" },
"t0934": { "name": "那須烏山", "population": 62531, "date_mod": "2003-8-17" }
}
次のファイルを書き換えます。
src/App.js
import React, { useState, useEffect } from 'react';
import './App.css';
function TableData() {
const [data, getData] = useState([])
const URL = 'https://example.com/cities.json';
useEffect(() => {
fetchData()
}, [])
const fetchData = () => {
fetch(URL)
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getData(response);
})
}
return (
<>
<h1>連想配列の表示</h1>
<table>
<thead>
<tr>
<th>no</th>
<th>key</th>
<th>name</th>
<th>population</th>
<th>date_mod</th>
</tr>
</thead>
<tbody>
{Object.keys(data).map((key, ii) => (
<tr key={ii}>
<td>{ii}</td>
<td>{key}</td>
<td>{data[key].name}</td>
<td>{data[key].population}</td>
<td>{data[key].date_mod}</td>
</tr>
))}
</tbody>
</table>
</>
);
}
export default TableData;