Open In App

Tilt effect in ReactJS

Creating a tilt effect in React JS typically involves applying styles dynamically based on user interaction, such as mouse movements. This tilt effect can enhance the UI of our web application so that it seems more realistic and better. We will do this using the Tilt Component from the “react-parallax-tilt” package/module.

Approach

We will need to use the Tilt Component from the ‘react-parallax-tilt’ package to show tilt effect for mouse hover on the card element. We can also modify the tilt behavior of our Tilt Component using its props. Below is a complete reference of the most generally used props to modify the default behavior of the Tilt Component as per our needs:



Creating React Application

Step 1: First of all, let’s create a simple react application using ‘create-react-app’. Open your command prompt or you can use a code editor like VSCode and use its command prompt and type the following command:

npx create-react-app foldername

Step 2: Move to the project directory



cd foldername

Step 3: Now install the ‘react-parallax-tilt’ package using npm.

npm i react-parallax-tilt

Project Structure

Your project should look like this

Folder Structure

Dependencies list after installing packages

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-parallax-tilt": "^1.7.171",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}

Example: Shows a card with tilt effect using react-parallax-tilt library in react js.




// Filename - App.js
 
import "./App.css";
import TiltComponent from "./TiltComponent";
 
function App() {
    return (
        <div id="background">
            <TiltComponent></TiltComponent>
        </div>
    );
}
 
export default App;




// Filename - TiltComponent.js
 
import React from 'react'
import Tilt from "react-parallax-tilt";
import "./TiltComponent.css";
 
const TiltComponent = () => {
    return (
        <Tilt glareEnable={true} tiltMaxAngleX={10}
        tiltMaxAngleY={10} perspective={1000}
        glareColor={"rgb(255,0,0)"}>
            <div className='tiltComponent'>
                {/* Your Code Here */}
            </div>
        </Tilt>
    )
}
 
export default TiltComponent;




/* Filename - App.css */
 
#background {
    width: 100%;
    height: 100%;
    background-color: rgb(19, 19, 59);
    position: absolute;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}




/* TiltComponent.css */
 
.tiltComponent {
    height: 400px;
    width: 700px;
    background-color: blue;
}

Steps to run the application: Write the below command in the terminal to run the application:

npm start

Output: Head towards your browser to see the output. If it’s not shown, go to ‘http://localhost:3000/‘ to see your output.

Output


Article Tags :