React and Hammer to build smooth swipe slider for mobile

15:40

I started to learn React a few days ago, but today I learned a lot. Ten hours of coding and fifteen minutes to take a break and eat.

This morning I had seen PhotoSwipe, and it had amazing performances. First I had though it is canvas, but it was NOT. I just needed to make my own, with same performances, and I thought it would be easy. I planned to use PhotoSwipe in my project, but it is complicated to customise to my specific needs.

I had wanted to get better in React and to see how Hammer works, so I chose Hammer, React and jQuery. The first prototype was made with jQuery and Hammer only, two predefined slides, lots of constants but it worked great on swipe left on a laptop.

Then I had included React and built React component. I was using Angular 1 before, and I must say that React is much more intuitive. Learning curve is higher than other front-end frameworks, and I like components. First time I heard about React I though it is silliness, but now I am changing my mind. There were few things I had not knew how to do, but I learned fast. Moment of truth, I opened a page on mobile, and it had much lower performance than PhotoSwipe.

Pain and sweat to get smooth performance. I had thought it was because of jQuery, so I removed it. That was hard. React + jQuery = super easy, React = pretty hard & lots of things to learn. I needed to replace $(node), css(), animate() and all these great and simple methods. I needed to rewrite all of it on "React way". Do you know that React has setState(), I didn't, I found out it is only way to manipulate with inline styles dynamically. Next challenge was children problem. I could not figure out how to get DOM node of children (look at the solution at the StackOverflow). I learned a lot about React. I ran on my mobile and again disappointment, still not fluid, I was losing hope. I tried to optimise JavaScript code, but there was still the same problem.

I was moving slides by changing "margin-left". I had done research, and I get an idea to replace "margin-left" with "transform: translate3d()". Eureka! It works!

I just found performances tests
https://jsperf.com/translate3d-vs-xy/57
As you can see "transform: translate3d()" is much faster than "margin-left" (35 times faster on my Chrome 45 on Ubuntu).

You can try component on mobile phone
http://lukicdarkoo.github.io/examples/react-light-swipe/index.html
it is in the early alpha stage; there is a lot of to do, but it is fast and smooth as I like.

You Might Also Like

0 коментара