Interacting With Dom Elements in React

John Eckert
Codezillas
Published in
2 min readJun 17, 2018

--

Earlier this week, I was building a React component that used content overflow to contain a bunch of smaller elements. I needed to allow the user to scroll left and right through them. Initially I used content overflow to add a scrollbar to the element

overflow-x: scroll;

As I was working on it, I decided that I really hated the scrollbar and the fact that it constantly made me double swipe back a page in the browser, while I was trying to navigate my content. It was not a great user experience!

It would be much better to have an arrow button on either side of my element (which I’m going to call container div) that allows the user to scroll through the component by clicking and disable the scrollbar completely. Getting rid of the scrollbar is as easy as changing the CSS to overflow-x: hidden; but, how could I make a button change the positioning of the content in my container div?

I decided to ask google. At first, I mostly found React packages and jQuery snippets for building carousels, but none of them actually did what I wanted. I was after a way to build it myself. Eventually, I found the Element.scrollLeft property.

According to MDN :

The Element.scrollLeft property gets or sets the number of pixels that an element's content is scrolled to the left.

Exactly what I needed! I could make a button that onClick increments or decrements the container div’s scrollLeft value.

Now I had a way to control the DOM element, but that was only half the battle. With React handling the DOM, I wasn’t able to grab it with any of the getElementBy functions, and there didn’t seem to be a way to access scrollLeft through my props.

A little searching in the React docs and I stumbled onto refs:

Refs provide a way to access DOM nodes or React elements created in the render method.

That sounded like exactly what I needed! I gave my container a prop of ref='scroller' and then in my onClick function for my button I was able to grab the container element with this.refs.scroller. Now I had access to the element, and it’s scrollLeft property! My final onClick methods (with a little error handling) looked like this:

I now had two operational scroll buttons and could disable that ugly scrollbar and save my users from accidentally swiping back a page on their touchpad. I’m kind of a hero!

--

--