Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Animated modal using react, framer-motion & styled-components
Next article icon

Animated sliding page gallery using framer-motion and React.js

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The following approach covers how to create an animated sliding page gallery using framer-motion and ReactJS.

Prerequisites:

  1. Knowledge of JavaScript (ES6)
  2. Knowledge of HTML and CSS.
  3. Basic knowledge of ReactJS.

Creating React Application And Installing Module:

Step 1: Create a React application using the following command:

$ npx create-react-app page-gallery

Step 2: After creating your project folder i.e. page-gallery, move to it using the following command.

$ cd page-gallery

Step 3: Add the npm packages you will need during the project.

$ npm install framer-motion @popmotion/popcorn

Open the src folder and delete the following files:

  1. logo.svg
  2. serviceWorker.js
  3. setupTests.js
  4. App.test.js (if any)
  5. index.css.

Create a file named PageSlider.js.

Project structure: The project structure tree should look like this:

Project structure

Filename: App.js

JavaScript
import React from "react"; import { useState } from "react"; import { motion, AnimateSharedLayout } from "framer-motion"; import PageSlider from "./PageSlider"; import "./styles.css";  const Pagination = ({ currentPage, setPage }) => {   // Wrap all the pagination Indicators    // with AnimateSharedPresence    // so we can detect when Indicators    // with a layoutId are removed/added   return (     <AnimateSharedLayout>       <div className="Indicators">         {pages.map((page) => (           <Indicator             key={page}             onClick={() => setPage(page)}             isSelected={page === currentPage}           />         ))}       </div>     </AnimateSharedLayout>   ); };  const Indicator = ({ isSelected, onClick }) => {   return (     <div className="Indicator-container" onClick={onClick}>       <div className="Indicator">         {isSelected && (           // By setting layoutId, when this component            // is removed and a new one is added elsewhere,            // the new component will animate out from the old one.           <motion.div className="Indicator-highlight"                       layoutId="highlight" />         )}       </div>     </div>   ); };  const pages = [0, 1, 2, 3, 4];  const App = () => {   /* We keep track of the pagination direction as well as     * current page, this way we can dynamically generate different     * animations depending on the direction of travel */   const [[currentPage, direction], setCurrentPage] = useState([0, 0]);    function setPage(newPage, newDirection) {     if (!newDirection) newDirection = newPage - currentPage;     setCurrentPage([newPage, newDirection]);   }    return (     <>       <PageSlider         currentPage={currentPage}         direction={direction}         setPage={setPage}       />       <Pagination currentPage={currentPage}                   setPage={setPage} />     </>   ); };  export default App; 

Filename: PageSlider.js

JavaScript
import React from "react"; import { useRef } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { wrap } from "@popmotion/popcorn";  // Variants in framer-motion define visual states // that a rendered motion component can be in at // any given time.  const xOffset = 100; const variants = {   enter: (direction) => ({     x: direction > 0 ? xOffset : -xOffset,     opacity: 0   }),   active: {     x: 0,     opacity: 1,     transition: { delay: 0.2 }   },   exit: (direction) => ({     x: direction > 0 ? -xOffset : xOffset,     opacity: 0   }) };  const pages = [0, 1, 2, 3, 4];  const PageSlider = ({ currentPage, setPage, direction }) => {   /* Add and remove pages from the array to checkout       how the gestures and pagination animations are       fully data and layout-driven. */   const hasPaginated = useRef(false);    function detectPaginationGesture(e, { offset }) {     if (hasPaginated.current) return;     let newPage = currentPage;     const threshold = xOffset / 2;      if (offset.x < -threshold) {       // If user is dragging left, go forward a page       newPage = currentPage + 1;     } else if (offset.x > threshold) {       // Else if the user is dragging right,        // go backwards a page       newPage = currentPage - 1;     }      if (newPage !== currentPage) {       hasPaginated.current = true;       // Wrap the page index to within the        // permitted page range       newPage = wrap(0, pages.length, newPage);       setPage(newPage, offset.x < 0 ? 1 : -1);     }   }    return (     <div className="slider-container">       <AnimatePresence         // This will be used for components to resolve         // exit variants. It's necessary as removed          // components won't rerender with          // the latest state (as they've been removed)         custom={direction}>         <motion.div           key={currentPage}           className="slide"           data-page={currentPage}           variants={variants}           initial="enter"           animate="active"           exit="exit"           drag="x"           onDrag={detectPaginationGesture}           onDragStart={() => (hasPaginated.current = false)}           onDragEnd={() => (hasPaginated.current = true)}           // Snap the component back to the center           // if it hasn't paginated           dragConstraints={{ left: 0, right: 0, top: 0, bottom: 0 }}           // This will be used for components to resolve all            // other variants, in this case initial and animate.           custom={direction}         />       </AnimatePresence>     </div>   ); };  export default PageSlider; 

Filename: App.css

CSS
body {   display: flex;   justify-content: center;   align-items: center;   min-height: 100vh;   overflow: hidden;   background: #09a960; }  * {   box-sizing: border-box; }  .App {   font-family: sans-serif;   text-align: center; }  .slider-container {   position: relative;   width: 600px;   height: 600px; }  .slide {   border-radius: 5px;   background: white;   position: absolute;   top: 0;   left: 0;   bottom: 0;   right: 0; }  /* position of indicator container */ .Indicators {   display: flex;   justify-content: center;   margin-top: 30px; }  .Indicator-container {   padding: 20px;   cursor: pointer; }  .Indicator {   width: 10px;   height: 10px;   background: #fcfcfc;   border-radius: 50%;   position: relative; }  .Indicator-highlight {   top: -2px;   left: -2px;   background: #09f;   border-radius: 50%;   width: 14px;   height: 14px;   position: absolute; } 

Step to Run Application: Run the application using the following command from the root directory of the project:

$ npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:


Next Article
Animated modal using react, framer-motion & styled-components
author
jt9999709701
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • CSS
  • ReactJS
  • Framer-motion

Similar Reads

  • Animated sliding image gallery using framer and ReactJS
    Animated sliding image gallery using Framer and React JS will have some image and show one by one by one with a sliding animation from right to left. Prerequisites:Node.js and NPM React JSReact JS HooksApproach:To design an animated sliding image gallery using Framer in React we will be using the Pa
    2 min read
  • Animated shared layout using framer-motion and React.js
    Animated shared layout using framer-motion and React.js involves items that toggle open and close show some animation/transitions and switch the states when clicked. Prerequisites:Node.js and NPMReact JSReact JS HooksApproach:To design an Animated shared layout using framer-motion and React.js we wi
    3 min read
  • Page transition in React.js using Framer Motion
    Page transition in React JS while switching and page loading in Routing adds extra animation to the web app. Framer motion provides customizable and easy-to-use animations and gestures for a better appearance and transition effects. PrerequisitesReact JSreact-router-dombootstrapFramer-motionApproach
    5 min read
  • Animated modal using react, framer-motion & styled-components
    In this article, we are going to learn how to create an animated model using react, framer-motion & styled-components. PrerequisitesJavaScript (ES6).HTMLCSSReactJS. React useStateSteps to Create React Application And Installing Module:Step 1: Now, you will start a new project using create-react-
    4 min read
  • Animated expanding card using framer-motion and ReactJS
    In this article, we are going to learn how to create an animated expanding card using react and framer. Prerequisites: Knowledge of JavaScript (ES6). JavaScript inbuilt methods we are going to make use are :Arrow function (ES6)Ternary operatorObjects in JavaScriptKnowledge of HTML/CSS.Basic knowledg
    4 min read
  • How to create a rolling die using React and framer-motion ?
    We can create a die using react with plain CSS and framer-motion library for animating, Framer Motion library helps to animate the UI elements. Prerequisites:JavaScriptHTMLCSSReactJSSteps to Create the React Application And Installing Module:Step 1: Create a React application using the following com
    3 min read
  • How to create Tinder card swipe gesture using React and framer-motion ?
    In the world of modern dating, Tinder has become one of the most popular platforms for meeting new people. One of its defining features is the swipe gesture, where users can swipe left or right to indicate their interest or disinterest in a potential match. In this article, we'll explore how to crea
    5 min read
  • Design an Animated Toggle Switch Button using framer-motion & React
    Animated Toggle Switch Button using framer-motion & React is a button that shows some animation/transitions and switches the states when clicked. Prerequisites:Node.js and NPM React JSReact JS HooksApproach:To design an animated toggle switch button using framer motion in react we will be using
    3 min read
  • Video Player and Gallery Using React and Tailwind
    A Video Player/Gallery is used to play a list of available videos on the browser, this helps the user to learn through visualization and is very helpful in reaching a large amount of audience effectively. Video Player is used generally by ed-tech companies to upload lectures online and provide demon
    5 min read
  • Animation and Transitions using React Hooks
    Animations allows to control the elements by changing their motions or display. Animation is a technique to change the appearance and behaviour of various elements in web pages. Transitions in CSS allow us to control the way in which transition takes place between the two states of the element. We c
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences