Bootstrap and base layout
The carousel is built as a React application, with styled-components handling presentation. The setup command is:
npx create-react-app react-easy-carousel
cd react-easy-carousel
yarn add styled-components
yarn install
yarn start
Predefined styled components are provided so styling doesn't distract from the carousel logic:
// App.styled.js
import styled from 'styled-components'
export const H1 = styled('h1')`
text-align: center;
margin: 0;
padding-bottom: 10rem;
`
export const Relative = styled('div')`
position: relative;
`
export const Flex = styled('div')`
display: flex;
`
export const HorizontalCenter = styled(Flex)`
justify-content: center;
margin-left: auto;
margin-right: auto;
max-width: 25rem;
`
export const Container = styled('div')`
height: 100vh;
width: 100%;
background: #ecf0f1;
`
export const Item = styled('div')`
color: white;
font-size: 2rem;
text-transform: capitalize;
width: ${({size}) => `${size}rem`};
height: ${({size}) => `${size}rem`};
display: flex;
align-items: center;
justify-content: center;
`
After stripping the App file down to essentials, a basic structure centers the carousel on the page:
// App.js
import {Carousel} from './Carousel'
function App() {
return (
<Container>
<H1>Easy Carousel</H1>
<HorizontalCenter>
<Carousel>
{/* Put your items here */}
</Carousel>
</HorizontalCenter>
</Container>
)
}
export default App
The layout itself is unremarkable — a centered carousel, nothing more.
Component anatomy
The component has two parts: an outer <div> that acts as the base container, and an inner block that serves as the scrollable area, making use of native scrolling.
// Carousel.js
<CarouserContainer>
<CarouserContainerInner>
{children}
</CarouserContainerInner>
</CarouserContainer>
Strict dimensions on the inner container are avoidable; wrapping it in a sized component keeps the layout flexible.
Native scrolling with CSS snap points
Smooth, clearly transitioning slides come courtesy of CSS scroll snapping: scrolling runs horizontally along the x-axis, and the scroll bar is hidden.
export const CarouserContainerInner = styled(Flex)`
overflow-x: scroll;
scroll-snap-type: x mandatory;
-ms-overflow-style: none;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
& > * {
scroll-snap-align: center;
}
`
scroll-snap-type and scroll-snap-align are native CSS that force an element to "snap" into place during a scroll. Here the snap type is set to the horizontal (x) direction with a stop at a snap position in the center of the element — in other words, scroll to the next slide and keep it centered in view.
Mechanically: the outer <div> lays its children (the slides) in a horizontal row, those children overflow the container width, and the container scrolls horizontally. Andy Adams, in the CSS-Tricks Almanac, describes scroll snapping as "locking" the viewport position to specific elements as the window or a scrollable container is scrolled, like a magnet on an element that sticks and forces scrolling to stop there. A demo is available on CodePen.
The container's children need a second property telling the browser where the scroll should stop — the magnet, in Adams's analogy, sits at the center of each slide:
& > * {
scroll-snap-align: center;
}
Testing is possible with a random array of items:
const colors = [
'#f1c40f',
'#f39c12',
'#e74c3c',
'#16a085',
'#2980b9',
'#8e44ad',
'#2c3e50',
'#95a5a6',
]
const colorsArray = colors.map((color) => (
<Item
size={20}
style={{background: color, borderRadius: '20px', opacity: 0.9}}
key={color}
>
{color}
</Item>
))
which is then dumped into the carousel:
// App.js
<Container>
<H1>Easy Carousel</H1>
<HorizontalCenter>
<Carousel>{colorsArray}</Carousel>
</HorizontalCenter>
</Container>
Spacing between items prevents a squeezed look. The first item otherwise carries unwanted space on its left, which a negative margin offsets:
export const CarouserContainerInner = styled(Flex)`
overflow-x: scroll;
scroll-snap-type: x mandatory;
-ms-overflow-style: none;
scrollbar-width: none;
margin-left: -1rem;
&::-webkit-scrollbar {
display: none;
}
& > * {
scroll-snap-align: center;
margin-left: 1rem;
}
`
Watch the cursor position while scrolling: it stays centered. That is scroll-snap-align at work.

The result accepts any number of items and simply works. Note that all of it is plain CSS, even though the host app is React — neither React nor styled-components is required for the scrolling behavior.
Adding prev/next navigation
The core carousel is flexible and scrolls through items, but the demo also has buttons that navigate between slides — that part needs JavaScript. Buttons sit on the left and right of the container and scroll to the previous or next slide; simple SVG arrow components are used:
// ArrowLeft
export const ArrowLeft = ({size = 30, color = '#000000'}) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M19 12H6M12 5l-7 7 7 7" />
</svg>
)
// ArrowRight
export const ArrowRight = ({size = 30, color = '#000000'}) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M5 12h13M12 5l7 7-7 7" />
</svg>
)
They are placed on both sides of the carousel:
// Carousel.js
<LeftCarouselButton>
<ArrowLeft />
</LeftCarouselButton>
<RightCarouselButton>
<ArrowRight />
</RightCarouselButton>
Absolute positioning pins the left arrow to the left edge and the right arrow to the right edge, with further styling to make them look like buttons. The container's :hover state toggles their visibility, so buttons appear only when the cursor is over the carousel.
// Carousel.styled.js
// Position and style the buttons
export const CarouselButton = styled('button')`
position: absolute;
cursor: pointer;
top: 50%;
z-index: 1;
transition: transform 0.1s ease-in-out;
background: white;
border-radius: 15px;
border: none;
padding: 0.5rem;
`
// Display buttons on hover
export const LeftCarouselButton = styled(CarouselButton)`
left: 0;
transform: translate(-100%, -50%);
${CarouserContainer}:hover & {
transform: translate(0%, -50%);
}
`
// Position the buttons to their respective sides
export const RightCarouselButton = styled(CarouselButton)`
right: 0;
transform: translate(100%, -50%);
${CarouserContainer}:hover & {
transform: translate(0%, -50%);
}
`
Showing both buttons at all times isn't desirable either: the left arrow should disappear on the first slide and the right arrow on the last, rather than implying navigation past the ends. A dedicated hook is the suggested home for all of this scrolling functionality, separating functional concerns from the visual component.
Tracking position with a ref
The component needs a reference to read slide positions, obtained via ref:
// Carousel.js
const ref = useRef()
const position = usePosition(ref)
<CarouserContainer>
<CarouserContainerInner ref={ref}>
{children}
</CarouserContainerInner>
<LeftCarouselButton>
<ArrowLeft />
</LeftCarouselButton>
<RightCarouselButton>
<ArrowRight />
</RightCarouselButton>
</CarouserContainer>
The ref sits on <CarouserContainerInner> because that element contains all items and enables correct calculations.
The hook tracks the next and previous items with a state for each:
// usePosition.js
export function usePosition(ref) {
const [prevElement, setPrevElement] = useState(null)
const [nextElement, setNextElement] = useState(null)
}
An update function then detects element positions and shows or hides the buttons. It runs inside React's useEffect so it fires on first DOM mount. The scrollable container is reachable at ref.current, assigned to a variable called element, and the element's DOM position is read with getBoundingClientRect(), which returns an element's position in the viewport for the calculations:
// usePosition.js
useEffect(() => {
// Our scrollable container
const element = ref.current
const update = () => {
const rect = element.getBoundingClientRect()
}, [ref])
getBoundingClientRect() serves double duty — the returned rect reveals both the element's size and its position relative to the viewport:

Next comes the math for determining which elements are visible inside the container:

Each item is filtered by comparing its viewport position against the container's boundaries: a child is visible if its left boundary is larger than the container's left boundary, and likewise on the right side. Step by step:
- Loop and filter through all container children using the
childrenproperty available on each node, converting it to an array first:
const visibleElements = Array.from(element.children).filter((child) => {}
- Read each element's position with
getBoundingClientRect()again:
const childRect = child.getBoundingClientRect()
- Assemble the logic:
rect.left <= childRect.left && rect.right >= childRect.right
The pieces together:
// usePosition.js
const visibleElements = Array.from(element.children).filter((child) => {
const childRect = child.getBoundingClientRect()
return rect.left <= childRect.left && rect.right >= childRect.right
})
With the visible items filtered, the hook checks whether an item is first or last so the matching button can be hidden. Two helpers test the condition using previousElementSibling and nextElementSibling: each checks whether a sibling exists in the list and whether it's an HTML instance, returning it if so. The first element comes from taking the first item in the visible list and checking for a previous node; the last works the same way, checking for a next element after the final item:
// usePosition.js
function getPrevElement(list) {
const sibling = list[0].previousElementSibling
if (sibling instanceof HTMLElement) {
return sibling
}
return sibling
}
function getNextElement(list) {
const sibling = list[list.length - 1].nextElementSibling
if (sibling instanceof HTMLElement) {
return sibling
}
return null
}
With both helpers in place, the hook checks for visible elements and sets the left and right button state:
// usePosition.js
if (visibleElements.length > 0) {
setPrevElement(getPrevElement(visibleElements))
setNextElement(getNextElement(visibleElements))
}
The function must also be called on every scroll through the list, which is when element positions need re-detecting:
// usePosition.js
export function usePosition(ref) {
const [prevElement, setPrevElement] = useState(null)
const [nextElement, setNextElement] = useState(null)
useEffect(() => {
const element = ref.current
const update = () => {
const rect = element.getBoundingClientRect()
const visibleElements = Array.from(element.children).filter((child) => {
const childRect = child.getBoundingClientRect()
return rect.left <= childRect.left && rect.right >= childRect.right
})
if (visibleElements.length > 0) {
setPrevElement(getPrevElement(visibleElements))
setNextElement(getNextElement(visibleElements))
}
}
update()
element.addEventListener('scroll', update, {passive: true})
return () => {
element.removeEventListener('scroll', update, {passive: true})
}
}, [ref])
The {passive: true} option is explained in this Stack Overflow writeup. The hook then returns these properties so the buttons update accordingly:
// usePosition.js
return {
hasItemsOnLeft: prevElement !== null,
hasItemsOnRight: nextElement !== null,
}
// Carousel.js
<LeftCarouselButton hasItemsOnLeft={hasItemsOnLeft}>
<ArrowLeft />
</LeftCarouselButton>
<RightCarouselButton hasItemsOnRight={hasItemsOnRight}>
<ArrowRight />
</RightCarouselButton>
// Carousel.styled.js
export const LeftCarouselButton = styled(CarouselButton)`
left: 0;
transform: translate(-100%, -50%);
${CarouserContainer}:hover & {
transform: translate(0%, -50%);
}
visibility: ${({hasItemsOnLeft}) => (hasItemsOnLeft ? `all` : `hidden`)};
`
export const RightCarouselButton = styled(CarouselButton)`
right: 0;
transform: translate(100%, -50%);
${CarouserContainer}:hover & {
transform: translate(0%, -50%);
}
visibility: ${({hasItemsOnRight}) => (hasItemsOnRight ? `all` : `hidden`)};
`
At this point the arrows appear and disappear dynamically according to scroll location in the list:

The final step is making the buttons functional: a function that accepts the next or previous element and scrolls to it.
const scrollRight = useCallback(() => scrollToElement(nextElement), [
scrollToElement,
nextElement,
])
const scrollLeft = useCallback(() => scrollToElement(prevElement), [
scrollToElement,
prevElement,
])
Functions should be wrapped in useCallback to avoid unnecessary re-renders.
The scrollToElement function is straightforward. Take the left boundary of the previous or next element (depending on which button was clicked), add the element's width divided by two to get the center position, and offset that value by half the container width. The result is the exact scrollable distance to the center of the next or previous element:

In code:
// usePosition.js
const scrollToElement = useCallback(
(element) => {
const currentNode = ref.current
if (!currentNode || !element) return
let newScrollPosition
newScrollPosition =
element.offsetLeft +
element.getBoundingClientRect().width / 2 -
currentNode.getBoundingClientRect().width / 2
currentNode.scroll({
left: newScrollPosition,
behavior: 'smooth',
})
},
[ref],
)
scroll performs the scrolling given that precise distance. The functions then attach to the buttons:
// Carousel.js
const {
hasItemsOnLeft,
hasItemsOnRight,
scrollRight,
scrollLeft,
} = usePosition(ref)
<LeftCarouselButton hasItemsOnLeft={hasItemsOnLeft} onClick={scrollLeft}>
<ArrowLeft />
</LeftCarouselButton>
<RightCarouselButton hasItemsOnRight={hasItemsOnRight} onClick={scrollRight}>
<ArrowRight />
</RightCarouselButton>
The working result:

Some tidying follows. Passed items can be controlled more directly with a little trick that automatically sends the required styles to each child — the Children API is worth a look:
<CarouserContainerInner ref={ref}>
{React.Children.map(children, (child, index) => (
<CarouselItem key={index}>{child}</CarouselItem>
))}
</CarouserContainerInner>
The styled components then need updating. flex: 0 0 auto preserves the original container sizes and is entirely optional:
export const CarouselItem = styled('div')`
flex: 0 0 auto;
// Spacing between items
margin-left: 1rem;
`
export const CarouserContainerInner = styled(Flex)`
overflow-x: scroll;
scroll-snap-type: x mandatory;
-ms-overflow-style: none;
scrollbar-width: none;
margin-left: -1rem; // Offset for children spacing
&::-webkit-scrollbar {
display: none;
}
${CarouselItem} & {
scroll-snap-align: center;
}
`
Accessibility notes
Functionality alone isn't enough; the component should be comfortable to use for everyone. Suggested improvements:
- Add
role='region'to highlight the significance of this area. - Add an
area-labelas an identifier. - Label the buttons so screen readers can identify them as "Previous" and "Next" and convey which direction each one moves.
// Carousel.js
<CarouserContainer role="region" aria-label="Colors carousel">
<CarouserContainerInner ref={ref}>
{React.Children.map(children, (child, index) => (
<CarouselItem key={index}>{child}</CarouselItem>
))}
</CarouserContainerInner>
<LeftCarouselButton hasItemsOnLeft={hasItemsOnLeft}
onClick={scrollLeft}
aria-label="Previous slide
>
<ArrowLeft />
</LeftCarouselButton>
<RightCarouselButton hasItemsOnRight={hasItemsOnRight}
onClick={scrollRight}
aria-label="Next slide"
>
<ArrowRight />
</RightCarouselButton>
</CarouserContainer>
Multiple carousels
Additional carousels can be dropped in to see how they behave with differently sized items — for example, a second carousel made from an array of numbers:
const numbersArray = Array.from(Array(10).keys()).map((number) => (
<Item size={5} style={{color: 'black'}} key={number}>
{number}
</Item>
))
function App() {
return (
<Container>
<H1>Easy Carousel</H1>
<HorizontalCenter>
<Carousel>{colorsArray}</Carousel>
</HorizontalCenter>
<HorizontalCenter>
<Carousel>{numbersArray}</Carousel>
</HorizontalCenter>
</Container>
)
}
Dump in a set of items and a fully working carousel comes out of the box.



