Skip to content

Instantly share code, notes, and snippets.

@limscoder
Last active November 20, 2017 19:21
Show Gist options
  • Save limscoder/6d7b458bce6b748986bfe79054d4f0da to your computer and use it in GitHub Desktop.
Save limscoder/6d7b458bce6b748986bfe79054d4f0da to your computer and use it in GitHub Desktop.
D3 rendering within a React component.
export default class Hexagons extends Component {
constructor(props) {
super(props);
// initialize array of hexData in state
this.state = { hexData: hexData() };
}
componentDidMount() {
// draw grid of hexagons with D3
this.hexGroup = d3.select(this.svg).append('g');
this.hexGroup.selectAll('.hex')
.data(this.state.hexData)
.enter()
.append('path')
.attr('class', 'hex')
.attr('d', hexPath)
.attr('fill', hexFill)
.attr('stroke', 'transparent')
.attr('stroke-width', 4)
.attr('transform', d => {
const cx = (d.col * r * 2) + (d.row % 2 ? r * 2 : r);
const cy = (d.row * r * 1.75) + r;
return `translate(${cx}, ${cy}) rotate(90 0 0)`;
});
// scale and center hexagon grid to fit screen
const svgBox = this.svg.getBoundingClientRect();
const hexBox = this.hexGroup.node().getBBox();
const scale = svgBox.height / hexBox.height;
const centerX = (svgBox.width / 2) - ((hexBox.width * scale) / 2);
this.hexGroup.attr('transform', `matrix(0, 0, 0, 0, ${centerX}, 0)`)
.transition()
.duration(transitionDuration)
.attr('transform', `matrix(${scale}, 0, 0, ${scale}, ${centerX}, 0)`)
}
render() {
// render svg element and use ref callback to store reference
return <svg ref={ svg => this.svg = svg } />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment