d3.js サンプル - Grid
呼び出し
sample.md
import SampleD3Grid from '@site/src/components/SampleD3Grid';
D3.js のサンプルです。
<SampleD3Grid>
□■■□□
□□■■□
■■■□□
</SampleD3Grid>
出力
D3.js のサンプルです。
コンポーネントの定義
src/components/SampleD3Grid.tsx
import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';
type Props = {
children: string;
};
const SampleD3Grid: React.FC<Props> = ({ children }) => {
const svgRef = useRef<SVGSVGElement | null>(null);
console.log(children.props.children)
useEffect(() => {
const lines = children.props.children
.trim()
.split('\n')
.map(line => line.trim());
const cellSize = 20;
const cellPadding = 0;
// const rows = lines.length;
// const cols = lines[0]?.length || 0;
const svg = d3.select(svgRef.current);
svg.selectAll('*').remove(); // 初期化
lines.forEach((line, rowIdx) => {
[...line].forEach((char, colIdx) => {
const fill = char === '■' ? '#4caf50' : '#eee';
svg
.append('rect')
.attr('x', colIdx * (cellSize + cellPadding))
.attr('y', rowIdx * (cellSize + cellPadding))
.attr('width', cellSize)
.attr('height', cellSize)
.attr('fill', fill)
.attr('stroke', '#999');
});
});
}, [children]);
return (
<svg
ref={svgRef}
width={500}
height={500}
style={{ display: 'block', margin: '0' }}
/>
);
};
export default SampleD3Grid;