Skip to content

Instantly share code, notes, and snippets.

@warrickct
Created April 16, 2018 22:35
Show Gist options
  • Save warrickct/892fefee042521cdc870167ba91e303d to your computer and use it in GitHub Desktop.
Save warrickct/892fefee042521cdc870167ba91e303d to your computer and use it in GitHub Desktop.
Draw d3 bar chart in React using react-faux-dom
import React, { Component } from 'react';
import * as d3 from 'd3';
import ReactFauxDOM from 'react-faux-dom';
class Chart extends React.Component {
constructor(props){
super();
this.state = {
data: [
{x: 1, y: 20},
{x: 2, y: 10},
{x: 3, y: 25},
{x: 4, y: 15},
],
}
}
drawChart() {
const div = new ReactFauxDOM.createElement('div');
//Sample data
let data = [
{x: 1, y: 20},
{x: 2, y: 10},
{x: 3, y: 25},
{x: 4, y: 15},
];
let margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 300 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
let x = d3.scaleBand()
.rangeRound([0, width]);
let y = d3.scaleLinear()
.range([height, 0]);
let xAxis = d3.axisBottom()
.scale(x)
let yAxis = d3.axisLeft()
.scale(y)
.ticks(10);
//Pass it to d3.select and proceed as normal
let svg = d3.select(div).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
x.domain(data.map((d) => d.x));
y.domain([0, d3.max(data, (d) => d.y)]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0,${height})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d) => x(d.x))
.attr("width", 20)
.attr("y", (d) => y(d.y))
.attr("height", (d) => { return height - y(d.y) });
//DOM manipulations done, convert to React
return div.toReact()
}
render() {
this.drawChart();
}
}
export default Chart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment