sinaptia waves

Dynamic horizontal slider using React and custom hooks

Lucas Belenda
Apr 5th, 2023

In frontend development, it’s very common for users to require the use of a horizontal slider, whether it’s for images, cards, information about articles on sale, etc. The first thing that comes to mind is to search for a pre-made solution, not “reinvent the wheel” and shorten development time. Libraries offer us a wide variety of tools that can make our work easier, but in my personal experience, none are accessible when trying to modify very specific characteristics, as is the case with design. In this blog post, I’ll share my experience developing a custom horizontal slider using React hooks, and how it allowed me to have full control over the design and behavior of the component.

The main challenges I faced when implementing my slider were: handling scroll events, responsive behavior, and touch events on mobile devices.

Why custom hooks were the perfect solution to my implementation?

Custom hooks are a way to extract and reuse logic in functional components in React. By creating a custom hook, you can encapsulate complex logic and reuse it in different components throughout your application. In my case, I found that implementing a custom hook for the horizontal slider was a good idea because it allowed me to separate the slider logic from the component rendering logic, making it easier to manage and maintain. Additionally, it made it easier to reuse the slider logic in other parts of the application if needed.

The hook returns an object with properties that allow the slider to be controlled: a ref to the slider element, a scrollTo function to scroll the slider left or right, a scrollStatus variable that represents the current scroll position of the slider and isOverflown, a function that indicates whether or not the slider content is overflowing its container, in my case this was used to hide or show the slider arrows when there are not enough elements on the list to do the scroll action.

Usage

In our example, we’re building an application that shows information about properties and the activities you can do while staying. We will create a <Slider> component that is designed to be reusable throughout the application while maintaining a consistent design structure. It will be able to receive different types of child components, such as activities you can do, pictures of properties to stay in, and so on.

As you can see in this code snippet, the <SimpleCard> components are passed as children to the <Slider>, which will handle the layout and scrolling of the elements ensuring consistency in the design and behavior.

If you like what you’re seeing and you want to try it out, you can install our npm package or check it out on GitHub. Contributions are welcome!