Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React renders d3 charts outside the body

I'm trying to generate a test environment to work on D3 using React.

I'm using the following code:

componentDidMount(){
    d3.select(this._testChart)
        .data(this.state.data)
        .enter().append('div')
        .style('background-color','blue')
        .style('color', 'white')
        .style('width', d=>d*10 + 'px')
        .text(d=>d)
}

render(){
    return (<div className='TestChart' ref={(c) => this._testChart = c}>
        </div>)
}

I'm getting the ref for the div, and then in componentDidMount(). I'm appending the div which generates a basic bar chart. Now, when I run this code, I'm seeing the bar chart, but it's getting rendered outside the body of the HTML. I guess I'm not using ref correctly. How can I get the chart inside the body?

like image 564
Vikram Avatar asked Jan 19 '26 07:01

Vikram


1 Answers

Your d3 selector should find the element by class name, not the React ref.

componentDidMount(){
    d3.select(".TestChart" )
        .data(this.state.data)
        .enter().append('div')
        .style('background-color','blue')
        .style('color', 'white')
        .style('width', d=>d*10 + 'px')
        .text(d=>d)
}

render(){
    return (<div className='TestChart' 
        </div>)
}
like image 113
Mark Avatar answered Jan 20 '26 21:01

Mark