10 Minutes building a React carousel base on React hook
--
Before we start, i think it’s necessary to talk about the reason i write this article. I hope i can help people who read this article easily build a carousel, get experiences applying React Hook to your project and how to make good use of ternary operator in React JSX. Don’t worry this is simple and you can finish it in 10 minutes for sure, let’s do it!
First step, we have to write a function component with React Hook. Before Hook introduced to the world in 2019, function components were stateless and logicless. Now with Hook we can achieve same goals as class component but write less code. Let’s check code:
Don’t forget to import useState and useEffect, with useState we can create state in function component and with useEffect we can handle state everytime our app renders. I created a state with useState called count and setCount is like setState function in class component. We can manage our state with it.
Let’s move on, i want four elements in our carousel. So i created four div blocks, each of them have a background color and the name of color on it. Appear like below. Feel free to create your own elements.
Now i want a carousel which switch its elements every 3 seconds. So we have to assign value of seconds to our state count. And use useEffect to set count every second. In that case we will get what we need and our counter will recalculate every time our app re-render. Let’s check code:
You can print out count to check if you are still with me. Now we want to show one of our elements every 3 seconds. Let’s do some simple math, divide count by 3(depends how many seconds you want to switch element) and make the result into integer by method parseInt(). It appear like below:
parseInt( count / 3)
And then we divide it by 4(depends how many elements in your carousel) and get its remainder. Here we go, this is what exactly we need. When remainder equal to 0 we show the first element; when remainder equal to 1 we show the second element, and so on.
parseInt( count / 3) % 4
Final step, we apply this value using ternary operator to manage whether to show the element or not. Let’s check code and how our carousel works:
Congratulations! Now we get a carousel and it’s totally customized. But it’s not the best thing yet, guess what? You created this by your own! Give yourself a warm applause!
Don’t forget to give me a clap if you think this is helpful! See you next time!