π¬ Build a Slideshow in React from Scratch
If you're looking to implement a simple slideshow feature in React without using third-party libraries, you can achieve it using React state and basic CSS styling.
βοΈ 1. React Slideshow Component
Hereβs a minimal React component for a text-based slideshow:
jsx
import React, { useState } from 'react';
import './Slideshow.css'; // For styling
const slidesData = [
{ id: 1, content: "Slide 1" },
{ id: 2, content: "Slide 2" },
{ id: 3, content: "Slide 3" },
];
const Slideshow = () => {
const [currentSlide, setCurrentSlide] = useState(0);
const goToNextSlide = () => {
setCurrentSlide((prev) => (prev === slidesData.length - 1 ? 0 : prev + 1));
};
const goToPrevSlide = () => {
setCurrentSlide((prev) => (prev === 0 ? slidesData.length - 1 : prev - 1));
};
return (
<div className="slideshow-container">
<button onClick={goToPrevSlide} className="prev">❮</button>
<button onClick={goToNextSlide} className="next">❯</button>
<div className="slide">
{slidesData.map((slide, index) => (
<div
key={slide.id}
className={index === currentSlide ? 'slide-content active' : 'slide-content'}
>
{slide.content}
</div>
))}
</div>
</div>
);
};
export default Slideshow;
π¨ 2. Styling the Slides (Slideshow.css
)
css
.slideshow-container {
position: relative;
max-width: 800px;
margin: auto;
}
.slide {
display: flex;
overflow-x: hidden;
}
.slide-content {
flex: 1;
display: none;
justify-content: center;
align-items: center;
text-align: center;
padding: 20px;
height: 300px;
background-color: #f2f2f2;
font-size: 24px;
}
.slide-content.active {
display: flex;
}
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
font-size: 24px;
background-color: rgba(0,0,0,0.5);
color: white;
border: none;
z-index: 1;
}
.prev { left: 0; }
.next { right: 0; }
π‘ Features Included
- Looping navigation (last β first, first β last).
- Simple, reusable component.
- Toggle slide visibility using the
active
class. - Style slides using CSS for responsiveness and presentation.
π§ Possible Enhancements
- Replace
content
with images or rich HTML. - Add auto-play functionality with
setInterval
. - Include dots or indicators for navigation.
- Add transition animations for a smoother experience.