Hello everyone! I am attempting to make the first D3.js project mobile responsive but I’m running into a few little snags.
When I view it on Codepen on my phone in Firefox or Chrome somehow overflow appears after I zoom the first time.
When I flip my phone to landscape mode I can’t see the whole graph
When I change the window size on desktop the external border gets thicker, oddly
Responsive D3 is not easy. It looks like you’re doing it manually with some resizing events and with CSS, and after thinking about this for just a few minutes I’m not real sure how those two methods would interact and I’m not at all surprised they have problems.
The size problems I believe are caused because the SVG gets a size on the initial render and then keeps it if you rotate or resize the screen. If the border is a percent or gets its state changed somehow, that may be changing its style. The only way to catch that that comes to mind is to inspect the element in the browser console before and after the change.
First, if you can try it away from codepen it may work better by removing that layer of complexity. If you can, I would try hosting it locally or on some free service (maybe repl.it) to see how it works without the codepen layer.
Second, visit the blog of Amelia Wattenberger and read the stuff on the D3 React hooks, with special attention to the
useChartDimensions hook and the
resize-observer module. I use those techniques to have responsive React/D3 components, but you can leave off the React stuff and just recycle the code to use resize-observer. Using resize-observer will allow the size of the SVG to update on screen size changes so that you just have to construct all the elements of the SVG relative to the overall size of the SVG.
I’ve used the D3 zoom functions before, but only for zooming on a graph and not for zooming the entire graph. I’m not sure they are the right tool for trying to make the SVG responsive, but you may be able to get them to work. For me, resize-observer has been the easiest technique.