Skip to content
Advertisement

Custom slider component in React is not working as expected

I am trying to improve my skills in React here and I wanted to build my portfolio, so I decided to have custom slider instead of using a library, so I use the following code:

JavaScript

It is working pretty fine except for two issues:

  1. After showing the last card I want arrow for next to not be clickable;
  2. After going next, and then clicking back to the very beginning, the arror for next is not clickable anymore. After refreshing the page, I am able again to go to the next cards.

Anyone any idea what can I improve on my code here?

Advertisement

Answer

To disable the “Next” button, add a conditional disabled flag to it. This example will disable the button when the state is equal to the total number of projects:

JavaScript

For your second problem, your function is currently setting the index to 0 once you reach the last slide. So you are on slide 5/5, but your function is setting the index to 0:

JavaScript

This is muddling the logic, so I would recommend removing updateIndex() entirely and writing your buttons like so:

JavaScript

Or – 1 for the back button.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement