Skip to main content

Stop the Image Slider on Mouse Hover & start slider again when mouse is out of the image in React js

To achieve this functionality we need to save the setInterval id in state ,

With the help of id we can stop the setInterval .

We will have two functions then one to start the setInterval or image slider .

Another to stop the Image slider or setInterval function.

Example : 

  const start = () => {
    console.log('start')
    const _start = setInterval(() => {
      setSelectedImage(selectedImage => selectedImage < 3 ? selectedImage + 1 : 0)
    }, 4000)
    setId(_start)
  }

  const stop = () => {
    console.log('stop')
    clearInterval(id)
  }

Now we need to call these functions on Mouse Over and Mouse Out Events Like :

 <img
        onMouseOut={() => start()}
        onMouseOver={() => stop()}
        width={810} height={400} src={allImages[selectedImage]} />

And On the component rendering we need to call the start function in useEffect Hook as follows :

  useEffect(() => {
    start()
  }, [])

And Interval id must be saved as Follows :

  const [id, setId] = useState(null)

This Id is saved when start function is called.

All Code in Sequence should be in App.js :

import { useEffect, useState } from "react";
import image1 from "./image/image1.png"
import image2 from "./image/image2.png"
import image3 from "./image/image3.jpg"
import image4 from "./image/image4.svg"

function App() {

  const [selectedImage, setSelectedImage] = useState(0)
  const [allImages, setAllImages] = useState([image1, image2, image3, image4])
  const [id, setId] = useState(null)

  useEffect(() => {
    start()
  }, [])

  const start = () => {
    console.log('start')
    const _start = setInterval(() => {
      setSelectedImage(selectedImage => selectedImage < 3 ? selectedImage + 1 : 0)
    }, 4000)
    setId(_start)
  }

  const stop = () => {
    console.log('stop')
    clearInterval(id)
  }

  return (
    <div>
      <img
        onMouseOut={() => start()}
        onMouseOver={() => stop()}
        width={810} height={400} src={allImages[selectedImage]} /> <br />
      <button
        onClick={() => {
          if (selectedImage > 0)
            setSelectedImage(selectedImage - 1)
        }}
      >PREV</button>

      <button
        onClick={() => {
          if (selectedImage < allImages.length - 1)
            setSelectedImage(selectedImage + 1)
        }}
      >NEXT</button>

    </div>
  );
}

export default App;


There are four images used , you can use any four images as used above and put them in image folder parallel to App.js File.


Follow the Video for More details :



Good Luck , Leave your comments here or below the video on youtube , Happy to help you .Keep Learning

Comments

Popular posts from this blog

Shopping Cart React.js Project with Explanation✅ [ Simple Ecommerce Website using Reactjs ]

Hello guys in this video we will discuss shopping cart web app.  first we need to install the basic react app using - npx create-react-app app-name The folder structure should be containing three files  in components folder as below : In App.js :  import './App.css' ; import Header from './components/Header' ; import ProductList from './components/ProductList' ; import CartList from './components/CartList' ; import { useState } from 'react' ; function App () {   const [ product , setProduct ] = useState ([     {       url : 'https://rukminim1.flixcart.com/image/300/300/l51d30w0/shoe/z/w/c/10-mrj1914-10-aadi-white-black-red-original-imagft9k9hydnfjp.jpeg?q=70' ,       name : 'TRQ White Shoes' ,       category : 'Shoes' ,       seller : 'AMZ Seller Ghz' ,       price : 1999     },     {       url : 'https://5.imimg.com/data5/KC/PC...

MERN Authentication - Login, Register, Verification Email, Forget Password, User Name & Logout on Navbar

In The React Side :  The folder structure will be : Lets start from App.js  On this file we will be adding routing , install the package react-router-dom : import './App.css' ; import React from 'react' ; import {   BrowserRouter as Router ,   Routes ,   Route ,   Link } from "react-router-dom" ; import Signup from './components/Signup' ; import Signin from './components/Signin' ; import Home from './components/Home' ; import ForgetPassword from './components/ForgetPassword' ; import NewSubmit from './components/NewSubmit' ; function App () {   return (     < div >       < Router >         < Routes >           < Route path = "/signup" element = { < Signup /> } />           < Route path = "/signin" element = { < Signin /> } />           < Route path = "/" e...

Create A Date Range Picker in React JS (By Saifi Code)

 To Create  A Date Range Picker in React JS , need to install following packages :  npm i antd npm i moment Step 1 : import DatePicker from antd and get RangePicker from this package Step 2 : In the JSX Use the package , you will start get picker ui Example :  To get the values use onChange method and save values in state  Try to console the state to check if the values are updating App.js File : import 'antd/dist/antd.css' ; import { DatePicker } from 'antd' ; import { useState } from 'react' ; import moment from 'moment' ; const { RangePicker } = DatePicker ; function App () {   const [ dates , setDates ] = useState ([])   console . log ( dates )     return (     < div style = { { margin : 20 } } >       < RangePicker         onChange = { ( values ) => {                     setDates ( values . map ( item => { ...