Build a “auto-resize” Carousel can fix to a certain item by react

Tsai Tim
2 min readMay 5, 2021

Ok. If we only want to make Carousel fulfill only one of features in title(auto-resize or fix a item) I think there are lot of examples if googling.
But what if we want both,
So I decide to show how to make a Carousel that is adaptive enough to have both features.

how to make hello1 always been shown in the screen while resizing? how about hello2, …?

Explaination(core)

Assume that we have 7 items: [1, 2, 3, 4, 5, 6, 7]
ItemNum = 7
currentScreenMaxItems = 4 //limited by the screen’s width
And we will use index to fix to a certain item.

#action 1(initial state)
update rowNum, colNum
recalc rowAt

1234 //visible
567 //hidden
{index: 0, rowAt: 0, rowNum: 2, colNum: 4}

#action 2(next)
rowAt < rowNum-1: allow click
index += colNum
rowAt += 1

1234 //hidden
567 //visible
{index: 4, rowAt: 1, rowNum: 2, colNum: 4}

#action 3(currentScreenMaxItems=5)
!detect resize
update rowNum, colNum
recalc rowAt

12345 //visible
67
{index: 4, rowAt: 0, rowNum: 2, colNum: 5}

#action 4(next)
!exception happened
rowAt(0)< rowNum(2)-1: allow click
but
index(4) + colNum(5) = 9 > ItemNum(7) -1
=>may have 2 solutions:
change index += colNum to
1. index = (rowAt + 1)*colNum
2. min(ItemNum, index + colNum)
here I choose (2.) because it can sort of memorizing position

12345
67 //visible
{index: 6, rowAt: 1, rowNum: 2, colNum: 5}

"""
here you may ask, does prev will also have this kind of situation?
base on the above logic,
if rowAt -= 1 is allowed,
it means that rowNum>=2,
we can guarantee that the prev row is always at full colNum
=>I think it’s impossible.
"""
#action 2(prev)
index -= colNum
rowAt -= 1

12345 //visible
67
{index: 1, rowAt: 0, rowNum: 2, colNum: 5}

Explaination(UI)

What kind of structure we can use for UI based on the observation in core?
3 methods I think is quite intuitive:
1. use flex with <hr> as line-break with translateY?
2. use grid with translateY?
3.use display none at start,
and only display block for the item we want,
can fully control every details?

And finally, I choose method (2.)
because for one of my current project is more maintainable

Code

https://github.com/tim08094495757/react-adaptive-carousel

--

--