Programming & Development / April 14, 2025

Creating a Basic Slideshow in React with State Management

React slideshow React carousel React state slide navigation next slide previous slide useState React components React UI

🎞️ React Basic Slide Component

This is a simple implementation of a slideshow in React using useState to manage the active slide.

🔧 1. Code Example

jsx

import React, { useState } from 'react';

const slides = [
  { id: 1, content: "Slide 1" },
  { id: 2, content: "Slide 2" },
  { id: 3, content: "Slide 3" },
  // Add more slides as needed
];

const BasicSlides = () => {
  const [currentSlide, setCurrentSlide] = useState(0);

  const goToNextSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === slides.length - 1 ? 0 : prevSlide + 1));
  };

  const goToPrevSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === 0 ? slides.length - 1 : prevSlide - 1));
  };

  return (
    <div className="basic-slides-container">
      <button onClick={goToPrevSlide}>Previous</button>
      <div className="slide-content">
        <h2>{slides[currentSlide].content}</h2>
      </div>
      <button onClick={goToNextSlide}>Next</button>
    </div>
  );
};

export default BasicSlides;

📋 How It Works

  • slides: An array containing slide objects with id and content.
  • useState: Keeps track of the current slide index.
  • goToNextSlide: Advances to the next slide, looping back to the start at the end.
  • goToPrevSlide: Moves to the previous slide, looping back to the last at the beginning.
  • The slide content and navigation buttons are rendered dynamically.

🎨 Optional Styling (CSS)

css

.basic-slides-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem;
}

.slide-content {
  font-size: 1.5rem;
  padding: 1rem 2rem;
  border: 2px solid #333;
  border-radius: 8px;
  background-color: #f0f0f0;
}

💡 Tips to Extend

  • Add images or rich content in slides.
  • Integrate auto-play using setInterval.
  • Include dot indicators for navigation.
  • Add transition animations for slide-in/slide-out effects.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex