Reusable way to create smooth tab highlights.

While developing the rebrand of my website I wanted a command bar using command + k. I came across a twitter post from Emil Kowalski about a way to smoothly transition the highlight when hovering over various elements.I decided this was perfect to implement as a nice to have in my command bar (cmd + k) when selecting various actions. The ‘problem’ arose when trying to implement this feature without repeating myself too many times in other projects and other places on this website (currently not, maybe soon). I decided to see if I can make a simple, small and easy to use way to implementing this feature across a react app.

And so useTabs is born.

I took the already existing code and transformed it into a hook that returns a function to set the highlight to the current ref or event, and returns an object containing the styling for the wrapper element.
const wrapperRef = useRef(null);

const { highlightStyles, setHighlight } = useTabs({
  container: wrapperRef,
By passing a event or a ref to the setHightlight() function, the hightlightStyles object gets updated with the height, width and position of the referenced element. You can then pass the highlightStyles to any HTML element to add some styling and have it automatically move to the ref element. In this example I am using TailwindCSS.
	className="bg-gray-500 bg-opacity-10 rounded-sm"
And that’s it. You can view the full example on the Github page.