Skip to content

Instantly share code, notes, and snippets.

@bguzryanto
Created December 31, 2015 21:34
Show Gist options
  • Save bguzryanto/120194574119024493ad to your computer and use it in GitHub Desktop.
Save bguzryanto/120194574119024493ad to your computer and use it in GitHub Desktop.
D3-Scale Example with React and NPMCDN
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://npmcdn.com/[email protected]"></script>
<script src="https://npmcdn.com/[email protected]"></script>
<script src="https://npmcdn.com/[email protected]/dist/react.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.min.js"></script>
<script src="https://d3js.org/d3-array.v0.6.min.js"></script>
<script src="https://d3js.org/d3-color.v0.3.min.js"></script>
<script src="https://d3js.org/d3-format.v0.4.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v0.3.min.js"></script>
<script src="https://d3js.org/d3-time.v0.1.min.js"></script>
<script src="https://d3js.org/d3-time-format.v0.2.min.js"></script>
<script src="https://d3js.org/d3-scale.v0.4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<style>
#root {
margin: 50px;
}
.bg-blue {
fill:#3498db;
}
#root text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const data = [5,10,15,20,25,30];
const { Component } = React;
const { render } = ReactDOM;
class Bar extends Component {
render() {
let {width, height, transform, text} = this.props;
return (
<g transform={transform}>
<rect className="bg-blue" width={width} height={height}></rect>
<text x={width-5} y={height/2} dy=".35em">{text}</text>
</g>
)
}
}
class App extends Component {
render() {
let { data, width } = this.props;
let barHeight = 30;
let height = barHeight * data.length;
const x = d3_scale.linear().domain([_.min(data), _.max(data)]).range([0,width]);
let bar = data.map((d, i) => {
return (
<Bar
key={i}
width={x(d)}
height={barHeight-1}
transform={`translate(0, ${i*barHeight})`}
text={d}
/>
)
});
return (
<div>
<h1>D3-Scale with react</h1>
<svg width={width} height={height}>
{bar}
</svg>
</div>
);
}
}
render(<App data={data} width="500" />, document.getElementById('root'));
</script>
<script>
(function() {
var source = document.querySelector('script[type="text/babel"]').innerText;
var output;
try{
output = Babel.transform(source, {
presets : ['es2015', 'react', 'stage-0']
}).code;
}catch(e){
output = 'Error: ' + e.message;
}
var script = document.createElement('script');
script.innerText = output;
script.type = 'text/javascript';
document.body.appendChild(script);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment