React.js made a Custom Line Chart

๐Ÿ‘:0

Here is simple example of SVG rendered with React:

const MyChart = ({points}) => {
  const lines = points.reduce((result, point, index) => {
    if (index === 0) return [];
    const previous = points[index - 1];
    const line = {x1: previous.x, y1: previous.y, x2: point.x, y2: point.y};
    return [...result, line];
  }, []);

  return (
    <svg width="200" height="200">
      
      {lines.map(({x1, x2, y1, y2}) => 
        <line x1={x1} x2={x2} y1={y1} y2={y2} stroke="blue" strokeWidth="2" />)
      }
      
      {points.map(({x, y}) => 
        <circle cx={x} cy={y} r="5" fill="red" />)
      }
    </svg>
  );
}


const data = [
  {x: 20, y: 100}, 
  {x: 50, y: 80},
  {x: 80, y: 50}
];

ReactDOM.render(<MyChart points={data} />, document.querySelector("#container"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>

Leave a comment