- Published on
How to Create a ReactJS Horizontal Scroll Webpage
- Authors
- Name
- Ripal & Zalak
How to Create a ReactJS Horizontal Scroll Webpage
Steps to Implement Horizontal Scrolling
1. Setup Your React Project with TailwindCSS
If you don’t already have a React project, create one using Vite:
npm create vite@latest horizontal-scroll --template react
cd horizontal-scroll
npm install
Install TailwindCSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
Configure tailwind.config.js
to include your project paths:
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [],
}
Add Tailwind to your CSS file (src/index.css
):
@tailwind base;
@tailwind components;
@tailwind utilities;
2. Build the Horizontal Scroll Layout
Update your App.jsx
file to include a container for the horizontally scrolling content. Here’s the code:
import React from 'react'
import './index.css'
function App() {
const handleScroll = (event) => {
const container = event.target
const scrollAmount = event.deltaY
container.scrollTo({
top: 0,
left: container.scrollLeft + scrollAmount,
behavior: 'smooth',
})
}
return (
<div className="flex h-screen flex-col">
<header className="flex h-16 items-center justify-center bg-blue-600 text-white">
<h1>Header</h1>
</header>
<div
className="flex-1 overflow-y-hidden overflow-x-scroll whitespace-nowrap"
onWheel={handleScroll}
>
<div className="inline-block h-full w-screen bg-red-500">Item 1</div>
<div className="inline-block h-full w-screen bg-green-500">Item 2</div>
<div className="inline-block h-full w-screen bg-yellow-500">Item 3</div>
<div className="inline-block h-full w-screen bg-purple-500">Item 4</div>
</div>
<footer className="flex h-16 items-center justify-center bg-gray-800 text-white">
<p>Footer</p>
</footer>
</div>
)
}
export default App
3. Customize the Scrollbar (Optional)
To style the scrollbar, use Tailwind’s CSS utilities and custom CSS. Add this to your index.css
file:
/* Custom scrollbar styles */
.scroll-container::-webkit-scrollbar {
height: 8px;
}
.scroll-container::-webkit-scrollbar-thumb {
background-color: #9ca3af;
border-radius: 4px;
}
.scroll-container::-webkit-scrollbar-track {
background-color: #e5e7eb;
}
Then, update the container class:
<div className="flex-1 overflow-x-scroll overflow-y-hidden whitespace-nowrap scroll-container" onWheel={handleScroll}>
FAQ
1. Why is the header and footer static?
By using flex
and h-screen
, the header and footer are given fixed heights while the scrollable container (flex-1
) takes up the remaining space.
2. How can I make the scrolling smoother?
Ensure you use behavior: 'smooth'
in the scrollTo
function to achieve smooth horizontal scrolling.
3. How do I test this locally?
Run the following command:
npm run dev
Open the browser at http://localhost:5173/
to view the webpage.