Animated modal using react, framer-motion & styled-components
In this article, we are going to learn how to create an animated modal using react, framer-motion & styled-components.
- Knowledge of HTML/CSS.
- Basic knowledge of ReactJS.
Framer-motion: The components and attributes we are going to make use of in this tutorial.
Creating React Application And Installing Module :
Step 1: Now, you will start a new project using create-react-app so open your terminal and type.
npx create-react-app toggle-modal
Step 2: After creating your project folder i.e. toggle-modal, move to it using the following command.
Step 3: Add the npm packages you will need during the project.
npm install framer-motion styled-components //For yarn yarn add framer-motion styled-components
Step 5: Now open your newly created project with your favorite code editor, I am using Visual Studio Code and will recommend you to use the same.
Open the src folder and delete the following files:
- App.test.js (if any)
Create a file named Styles.js.
Project structure: Your folder structure tree should look like this.
- We are going to create a Modal component with ‘showModal’ prop only to manage its state of visibility and animated using framer-motion AnimatePresence.
- AnimatePresence allows components to animate out when they’re removed from the React tree and to enable exit animations.
- To give spring animation to modal container we will use framer-motion spring animation with stiffness = 300.
- Content of modal is geeksforgeeks image which is also animated using framer-motion motion.div.
- React useState hook to manage the state of ‘showModal’ i.e. responsible to toggle the modal container.
- ‘displayModal’ utility function to set the ‘showModal’ value opposite of its last value to toggle modal.
- Event listener for document body so that on clicking outside or on the modal, ‘showModal’ is set to false and in turn modal is disappeared.
- ToggleBtn is also animated using framer-motion motion.button.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.