Question

Trying to convert Mike Bostock's zoomable treemap into React components. Part of the way there but not sure about the best way to pass around data between components when that data depends on the rendered DOM (i.e. width).

Came across Ben Smith's blog about mixing React and D3js. Great stuff.

Using Bootstrap to control the CSS styling. Defined the svg element with an absolute position and max width (100%) inside a relative container:

 .svg-container {
   position: relative;
   padding-bottom: 30%;
   overflow: hidden;
   }

 .svg-content {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
 } 

So the width of the svg element changes as the screen is resized. Assuming that the treemap node attributes like x,y,dx,dy have to fixed values not procents. Thinking I have to watch the window's resize event, pick off the new svg element dimensions ("parseInt(d3.select('.svg-content').style('width'), 10);") and force Reactjs to re-render ("React.renderComponent").

Was it helpful?

Solution

You have two choices:

  • give the current height and width to the treemap layout, and recalculate the treemap every time the height and width change; or,

  • calculate the treemap layout with the default size (the maximum height and width will be 1, everything else a proportion thereof), and use the current height and width as a scaling factor when you draw the rectangles.

Then, when the height or width changes, you only need to redraw, not recalculate the layout. Since you're trying to keep different components separate, that seems the most sensible approach. It also is just more efficient, since you're only running the layout function once. You can just grab the current height and width from within your redraw function (which will of course have access to the svg node) and the layout component doesn't need to know anything about the dimensions.

Oh, and I'm afraid parseInt(d3.select('.svg-content').style('width'), 10); won't do what you're hoping, that only returns inline styles. You'll need to grab the computed width. There are some examples of how to do it at the end of this long answer on zooming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top