Trying to create a simple bar chart using d3.js . I have also gone ahead and provided a button to create random data to be used as the dataset for the svg bar chart. However, the bars in svg only render for the first dataset. Even though i change the values for datasets, the bar chart remains the same. Help needed.
I checked the props to see if they were changing. the props were updating, but wasn't changing the bars in the chart.
App.js file :
class App extends Component {
constructor(props){
super(props)
this.state={
dataSet: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
}
}
dataSetCreator = () =>{
let n = Math.ceil(Math.random()*10);
this.setState({
dataSet : [...Array(n)].map(_=>Math.ceil(Math.random()*10))
})
}
render() {
console.log(this.state.dataSet)
return (
<div className="App">
<div className="d3-chart">
<span>Bar Chart With D3</span>
<BarChart
data={this.state.dataSet}
height={500}
width={500}/>
<button onClick={()=>this.dataSetCreator()}>Change Data</button>
</div>
</div>
);
}
}
BarChart.js:
class BarChart extends Component{
componentDidMount(){
this.createBarChart();
}
componentDidUpdate(){
this.createBarChart();
}
createBarChart = ()=>{
const svgWidth = this.props.width
const svgHeight = this.props.height;
var svg = d3.select('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
.attr('class', 'bar-chart');
debugger
var dataset = this.props.data;
var barPadding = 5;
var barWidth = (svgWidth / dataset.length);
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('y', (d)=>svgHeight-(d*5))
.attr('height', (d)=>d*5)
.attr('width', barWidth-barPadding)
.attr('transform', (d, i)=>{
var translate = [barWidth*i, 0];
return "translate(" + translate + ")"
})
}
render(){
console.log(this.props.data)
return(
<svg>
</svg>
);
}
}