Top React Hooks — Outside Clicks and Dimensions

Image for post
Image for post
Photo by Free To Use Sounds on Unsplash

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

React Cool Dimensions

React Cool Dimensions lets us watch the dimension of a component.

To use it, we install it by running:

or

Then we can use it by writing:

We use the useDimensions hook which returns the ref that we can assign to the element we want to watch the size for.

Then dimensions has the object with width and height of the element we’re watching.

onResize is a method that runs when we resize the element.

We can also assign breakpoints so the hook can determine the breakpoint when watching the element size.

For instance, we can write:

We added the breakpoints property to get the breakpoints according to what we assigned.

All the dimensions are in pixels.

We can include the border size with the measurement.

For instance, we can write:

Then the border is included with the measurements.

To throttle the watching, we can throttle the onResize callback calls with the Lodash throttle method.

We can also create our own ref and pass it into the useDimensions hook’s object argument’s ref property.

React Cool Onclickoutside

React Cool Onclickoutside lets us detect clicks outside an element.

To install it, we run:

or:

Then we can use it by writing:

useOnclickOutside is the hook that comes with the package to detect clicks outside an element.

It returns a ref which we can pass into the ref prop of the element we want to watch the clicks outside for.

Now when we click outside the menu div, the menu will disappear.

Image for post
Image for post
Photo by Cristina Anne Costello on Unsplash

Conclusion

React Cool Dimensions lets us watch the dimensions of our elements.

React Cool Onclickoutside lets us detect clicks that are outside an element.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store