D3 - React

Card Puncher Data Processing

About

D3 in react

Example

By using the ref attribute

class LineChart extends React.Component {

  constructor(props) {
     super(props); // Always call the base constructor with props.
  }
  render() {
    data=props.data;
    const margin = {top: 10, right: 20, bottom: 20, left: 30};
    const width = 500;
    const height = 300;
    const x = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.x)])
        .range([margin.left, width - margin.right]);
    const y = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.y)])
        .range([height - margin.bottom, margin.top]);
    return htm`
      <svg width=${width} height=${height}>
        <path 
          fill="none" 
          stroke="#33C7FF" 
          stroke-width="2" 
          d=${d3.line().x(d => x(d.x)).y(d => y(d.y))(data)} />
        <g 
          transform="translate(${margin.left},0)" 
          ref=${g => d3.select(g).call(d3.axisLeft(y))} />
        <g 
          transform="translate(0,${height - margin.bottom})" 
          ref=${g => d3.select(g).call(d3.axisBottom(x))} />
      </svg>
    `;
  }
}

data = [
  {x: 0, y: 10}, 
  {x: 10, y: 40}, 
  {x: 20, y: 30}, 
  {x: 30, y: 70}, 
  {x: 40, y: 0}
]

Documentation / Reference







Share this page:
Follow us:
Task Runner