Integrating the Hook with Your Graph
Our use-dimensions
hook monitors changes in a div
's dimensions and returns those values. Now, let’s use this hook to feed the dimensions directly into our graph!
1️⃣ Create a Ref
Begin by creating a ref
with the React useRef()
function.
A ref
lets you directly target and interact with a specific HTML element in your app’s DOM. Remember, we covered this concept in the module on D3.js axes.
const chartRef = useRef(null);
Finally, pass the chartRef
to the container you want to monitor.
return(
<div ref={chartRef}>
<MyChartComponent
height={chartSize.height}
width={chartSize.width}
</div>
)
2️⃣ Use the hook
Then, pass this newly created chartRef
to the hook:
const chartSize = useDimensions(chartRef);
You now have an object called chartSize
with two properties: height
and width
. These properties can be used in your chart component. 🔥
Pro tip: Before building a responsive visualization, useconsole.log()
to check thechartSize
object and ensure everything is working correctly.
📊 Application
You’re all set!
Just pass the values from chartSize
to the visualization component, and it will become responsive.
Here is a full example with code: