GithubHelp home page GithubHelp logo

mkosir / react-parallax-tilt Goto Github PK

View Code? Open in Web Editor NEW
910.0 19.0 109.0 98.61 MB

๐Ÿ‘€ Easily apply tilt hover effect on React components - lightweight/zero dependencies (3kB)

Home Page: https://mkosir.github.io/react-parallax-tilt

License: MIT License

TypeScript 89.52% JavaScript 3.05% CSS 7.43%
parallax typescript react-library react tilt parallax-effect react-tilt gyroscope

react-parallax-tilt's Introduction

React Tilt

npm version npm downloads npm bundle size Open issues TypeScript semantic-release

CI CI CI CI CI Codecov Coverage

CI CI

๐Ÿ‘€ Easily apply tilt hover effect on React components

Install

npm install react-parallax-tilt

Features

  • Lightweight (โ‰ˆ3kB), zero dependencies ๐Ÿ“ฆ
  • Tree-shakable ๐ŸŒณ ESM and CommonJS support
  • Works with React v15 onwards
  • Supports mouse and touch events
  • Support for device tilting (gyroscope)
  • Glare effect ๐ŸŒŸ with custom props (color, position,...) ๐Ÿ”—demo
  • Events to keep track of component values ๐Ÿ“ (tilt, glare, mousemove,...) ๐Ÿ”—demo
  • Many effects that can be easily applied:

Example

import React from 'react';
import ReactDOM from 'react-dom';
import Tilt from 'react-parallax-tilt';

const App = () => {
  return (
    <Tilt>
      <div style={{ height: '300px', backgroundColor: 'darkgreen' }}>
        <h1>React Parallax Tilt ๐Ÿ‘€</h1>
      </div>
    </Tilt>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

Props

All of the props are optional.
Below is the complete list of possible props and their options:

โ–ถ๏ธŽ indicates the default value if there's one

tiltEnable: boolean โ–ถ๏ธŽ true
Boolean to enable/disable tilt effect.

tiltReverse: boolean โ–ถ๏ธŽ false
Reverse the tilt direction.

tiltAngleXInitial: number โ–ถ๏ธŽ 0
Initial tilt value (degrees) on x axis.

tiltAngleYInitial: number โ–ถ๏ธŽ 0
Initial tilt value (degrees) on y axis.

tiltMaxAngleX: number โ–ถ๏ธŽ 20
Max tilt rotation (degrees) on x axis (range: 0ยฐ-90ยฐ).

tiltMaxAngleY: number โ–ถ๏ธŽ 20
Max tilt rotation (degrees) on y axis (range: 0ยฐ-90ยฐ).

tiltAxis: 'x' | 'y' โ–ถ๏ธŽ undefined
Enable tilt on single axis.

tiltAngleXManual: number | null โ–ถ๏ธŽ null
Manual tilt rotation (degrees) on x axis.

tiltAngleYManual: number | null โ–ถ๏ธŽ null
Manual tilt rotation (degrees) on y axis.

glareEnable: boolean โ–ถ๏ธŽ false
Boolean to enable/disable glare effect.

glareMaxOpacity: number โ–ถ๏ธŽ 0.7
The maximum glare opacity (range: 0-1).

glareColor: string โ–ถ๏ธŽ #ffffff
Set color of glare effect.

glareBorderRadius: string โ–ถ๏ธŽ 0
Accepts any standard CSS border radius. Useful if the glare color is different to the page color.

glarePosition: 'top' | 'right' | 'bottom' | 'left' | 'all' โ–ถ๏ธŽ bottom
Set position of glare effect.

glareReverse: boolean โ–ถ๏ธŽ false
Reverse the glare direction.

scale: number โ–ถ๏ธŽ 1
Scale of the component (1.5 = 150%, 2 = 200%, etc.).

perspective: number โ–ถ๏ธŽ 1000
The perspective property defines how far the object (wrapped/child component) is away from the user. The lower the more extreme the tilt gets.

flipVertically: boolean โ–ถ๏ธŽ false
Boolean to enable/disable vertical flip of component.

flipHorizontally: boolean โ–ถ๏ธŽ false
Boolean to enable/disable horizontal flip of component.

reset: boolean โ–ถ๏ธŽ true
If the effects has to be reset on onLeave event.

transitionEasing: string โ–ถ๏ธŽ cubic-bezier(.03,.98,.52,.99)
Easing of the transition when manipulating the component.

transitionSpeed: number โ–ถ๏ธŽ 400
Speed of the transition when manipulating the component.

trackOnWindow: boolean โ–ถ๏ธŽ false
Track mouse and touch events on the whole window.

gyroscope: boolean โ–ถ๏ธŽ false
Boolean to enable/disable device orientation detection.

onMove: ({ tiltAngleX: number, tiltAngleY: number, tiltAngleXPercentage: number, tiltAngleYPercentage: number, glareAngle: number, glareOpacity: number, eventType: string }) => void
Gets triggered when user moves on the component.

onEnter: (eventType: string) => void
Gets triggered when user enters the component.

onLeave: (eventType: string) => void
Gets triggered when user leaves the component.

Gyroscope - Device Orientation

Please keep in mind that detecting device orientation is currently experimental technology.
Check the browser compatibility before using this in production.
A few takeaways when using device orientation event:

  • always use secure origins (such as https)
    • if you're using VS Code, then you can
      • use the in-built port-forwarding feature to expose your localhost to the internet and optionally change the protocol to https
      • alternatively, use microsoft's live-share extension which supports sharing server through a tunnel.
  • it doesn't work in all browsers when using it in cross-origin <iframe> element
Using device orientation on iOS 13+

Apple decided turning device motion and orientation off by default since iOS 12.2.
With iOS 13+ permission API can be used to gain access to device orientation event.

When using gyroscope feature:

<Tilt gyroscope={true}>
  <h1>React Parallax Tilt ๐Ÿ‘€</h1>
</Tilt>

it will present a permission dialog prompting the user to allow motion and orientation access at domain level:

Note that user needs to take some action (like tapping a button) to be able to display the dialog (invoking dialog on page load is not possible).

Development

Easily set up a local development environment!

Build project and start storybook on localhost:

  • clone
  • npm install
  • npm start

Start coding! ๐ŸŽ‰

Or setup with npm link Clone this repo on your machine, navigate to its location in the terminal and run:
npm install
npm link # link your local repo to your global packages
npm run build:watch # build the files and watch for changes

Clone project repo that you wish to test with react-parallax-tilt library and run:

npm install
npm link react-parallax-tilt # link your local copy into this project's node_modules
npm start

Contributing

All contributions are welcome!
Please take a moment to review guidelines PR | Issues

react-parallax-tilt's People

Contributors

anweshgangula avatar dependabot-preview[bot] avatar dmanexe avatar elmarti avatar lalit2005 avatar lucasfrsi avatar lucidninja avatar lyricwulf avatar mkosir avatar mrtnli avatar ndom91 avatar renovate-bot avatar sumanthratna avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-parallax-tilt's Issues

Cannot read property 'style' of null

Hi,

I keep getting this error when my app hot reloads after a change.
Here is my code:

const { loading, error, data } = useFetch(getBannersAPI, fetchId);
let content;
	if (loading) {
		content = <Loading />;
	} else if (error) {
		content = <Error>{error.message}</Error>;
	} else if (data?.data?.rows?.length > 0) {
		content = (
			<div className='banner-container'>
				{data?.data?.rows.map(({ id, name, image_url }) => (
					<Card key={id} className='bg-dark'>
						<Tilt scale={0.97}>
							<Card.Img variant='top' src={image_url} />
						</Tilt>
						<Card.Body className='pb-0 text-light'>
							<Card.Title className='d-flex justify-content-between'>
								<strong>{name}</strong>
								<section>
									<IconButton
										title='Edit Banner'
										onClick={() => toggleSaveBannerModal({ id, name, image_url })}
									>
										<InlineIcon icon={bxsEditAlt} color='cornflowerblue' />
									</IconButton>

									<IconButton title='Delete Banner' onClick={() => deleteBannerHandler(id)}>
										<InlineIcon icon={delete24Filled} color='firebrick' />
									</IconButton>
								</section>
							</Card.Title>
						</Card.Body>
					</Card>
				))}
			</div>
		);
	} else {
		content = <NoData>No Banner Found!</NoData>;
	}

How to fix this issue?

If the functional component re-render it takes random position

๐Ÿ› Random transform rotate position on re-render

I used my tilt component on a child component, when I change any state value from the parent component then my tilt move some random position.

By default the style value of the tilt element is transform: perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)

but once the component re-render then the tilt element's style value is transform: perspective(1000px) rotateX(-20deg) rotateY(20deg) scale3d(1, 1, 1) by default

App.js (Parent component)

import React from 'react';
import SideMenu from "./Components/SideMenu";

function App() {
  const [test, setTest] = React.useState(0);
  setTimeout(()=>{
     setTest(test + 1);
  }, 2000);
  return (
    <>
      <SideMenu />
    </>
  );
}
export default App;

SideMenu.js (Child component)

import React from "react";
import Tilt from 'react-parallax-tilt';
import "./SideMenu.scss";

function SideMenu() {

  const [tilt, setTilt] = React.useState({
    className: 'menu',
    glareEnable: true,
    scale: 1.05,
    glareMaxOpacity: 0.05,
    glareColor: 'white',
    glarePosition: 'all'
  });

  return <aside>
    <nav>
      <Tilt {...tilt} >
        <a href="/" className="link">
          <i className="mdi mdi-spider-web" />
          <span>Dashboard</span>
        </a>
      </Tilt>
    </nav>
  </aside>
}

export default SideMenu;

SCSS code

nav {
    display: flex;
    flex-wrap: wrap;
    .menu{
      position: relative;
      width: 50%;
      height: 120px;
      border-radius: 6px 6px 0 0;
      transform-style: preserve-3d;
      i {
        transform: translateZ(20px);
        display: block;
        font-size: 36px;
      }
      span{
        transform: translateZ(30px);
        font-weight: 100;
      }
      .link {
        width: 100%;
        height: 120px;
        color: #ffffff;
        text-decoration: none;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: relative;
        z-index: 1;
      }
    }

glareReverse not working

๐Ÿ› Issue/Bug Report Template

Describe the bug
If glareReverse is enabled it won't work. The glare would never show. If I change the glarePosition to "bottom" or "top", as long as it is not set to "all", the glare would come back but it is not reversed still.

Expected behavior
If you hover on the top-right, the glare should be at the bottom areas.

Code snippets
Inside React app...

return (
    <div className="wrapper">
        <Tilt glareReverse glareEnable glareMaxOpacity={0.4} glareColor="#ffffff" glarePosition="all">
            <img src="./testImage.jpg" />
        </Tilt>
    </div>
  );

Inside the scss file...

.wrapper {
  padding: 1px;
  width: 90%;
  height: auto;
  margin: 0 auto;
  border-radius: 10px;

  img {
    width: 100%;
    border-radius: 9px
  }
}

Environment

  • Browser: Chrome
  • Version: "react-parallax-tilt": 1.4.66
  • ...

Additional context
Add any other context about the problem here.

Glare on rectangle shape

๐Ÿ› Issue/Bug Report Template

Describe the bug
Glare seems not it should
image

To Reproduce

<Tilt
  style={{
    background: "black",
    width: 380,
    height: 180
  }}
  perspective={500}
  glareEnable={true}
  glareMaxOpacity={0.5}
  scale={0.9}
>
    <div>hello</div>
</Tilt>

Expected behavior
A clear and concise description of what you expected to happen.
I guess it shouldn't have a black spot down there. if make it a square glare seem fine.

Link to demo (required)
Please provide demo in online code editor CodeSandbox or similar.
https://codesandbox.io/s/cranky-haze-9mo54?file=/src/App.js

Issues without a reproduction link are likely to stall.

Code snippets
If applicable, add code samples to help explain your problem.

<>
  <Tilt
    style={{
      background: "black",
      width: 380,
      height: 180
    }}
    perspective={500}
    glareEnable={true}
    glareMaxOpacity={1}
    scale={0.9}
  >
    <div
      style={{
        color: "white"
      }}
    >
      RECTANGLE'S GLARE IS SEEM NOT RIGHT
    </div>
  </Tilt>
  <br />
  <Tilt
    style={{
      background: "black ",
      width: 380,
      height: 380
    }}
    perspective={500}
    glareEnable={true}
    glareMaxOpacity={1}
    scale={0.9}
  >
    <div
      style={{
        color: "white"
      }}
    >
      SQUARE'S GLARE IS FINE
    </div>
  </Tilt>
</>

Environment

  • Browser: Chrome
  • Version: "react-parallax-tilt": 1.4.66
  • ...

Additional context
Add any other context about the problem here.

Tilt causes crash in Next.js

Description

In Next.js any use of tilt causes an error (seen below):
TypeError: Cannot read properties of undefined (reading 'PureComponent')
at e (file:///vercel/path0/node_modules/react-parallax-tilt/dist/index.js:1:4112)
at file:///vercel/path0/node_modules/react-parallax-tilt/dist/index.js:1:10860
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Build error occurred
Error: Failed to collect page data for /
at /vercel/path0/node_modules/next/dist/build/utils.js:1220:15 {
type: 'Error'

Link to Reproduction - Please provide demo in online code editor CodeSandbox or similar. - Issues without a reproduction link are likely to stall.

N/A

Steps to reproduce

  1. Make a next.js project
  2. Import react parallax tilt
  3. Run npx next build
  4. Get error

Expected behavior

ESLint to pass

React Parallax Tilt Version

1.7.185

Custom transitionSpeed value cancelled after certain time or mousevents

๐Ÿ› Custom transitionSpeed value cancelled after certain time or mousevents

Describe the bug
My custom set transition speed value is cancelled/bypassed after certain time or maybe (?) mousevents. It very noticeably switches from being smoothed to instantly responding. Upon moving the cursor outside and then inside the element the issue is (temporarily) resolved.

To Reproduce
Steps to reproduce the behavior:

  1. Create a <Tilt /> component
  2. Set a custom transitionSpeed prop
  3. Wiggle your mouse around for a few seconds (while staying within the frame)
  4. The transition speed is now instant
  5. Move the cursor outside the component, then back in
  6. Works again, but then issue repeats when you stay inside again

Expected behavior
I expect the transition speed to stay slow for as long as the prop is not unset

Link to demo (highly encouraged)
CodeSandbox demo.

Code snippets
If applicable, add code samples to help explain your problem.

Environment

  • Browser: Chrome 85.0.4183.121 on Windows 10
  • Version: "react-parallax-tilt": tested 1.0.13 and (currently latest) 1.4.65

Additional context
I expect it has to do with specifically higher values for transition speed, but it might also be an effect of the change being more noticeable.

Initial tilt doesn't work (tilts to a random XY on refresh)

๐Ÿ› Issue/Bug Report Template

Describe the bug

Thanks for this amazing package!

To Reproduce
Steps to reproduce the behavior:

  1. Go down to the
  2. refresh site
  3. The tilt doesn't comply with reset or tiltAngleXInitial, tiltAngleYInitial

Expected behavior
A clear and concise description of what you expected to happen.

Link to demo (highly encouraged)

Reproducible example coming soon!

Code snippets

Environment

Chrome

Additional context
Add any other context about the problem here.

Glare prevents clicks

๐Ÿ› Issue/Bug Report Template

Describe the bug
Turning on the glare prevents clicks on nested components from triggering.

To Reproduce
Steps to reproduce the behavior:

<Tilt glareEnable>
  <div
    style={{backgroundColor: "gray", height: 100}}
    onClick={() => alert("hello")}
  />
</Tilt>

You can fix this with:

.glare-wrapper { pointer-events: none; }

Expected behavior
Should get an alert saying hello

Link to demo (highly encouraged)
See above. Easily reproducible.

  • Browser: Chrome
  • Version: "react-parallax-tilt": 1.4.66
  • ...

Missing type declarations

Description

Could not find a declaration file for module 'react-parallax-tilt'. 'C:/Users/alany411/Documents/GitHub/react-parallax-tilt-bug/node_modules/react-parallax-tilt/dist/index.umd.js'

I checked out the package in the node_modules folder and noticed that the types were in a nested folder named dist, but in the package.json, it was "types": "./dist/types/index.d.ts",

node_modules folder

package.json

You can also browse the files through RunKit and see the same:

runkit

Link to Reproduction

Fresh repo:
https://github.com/alany411/react-parallax-tilt-bug

RunKit:
https://npm.runkit.com/react-parallax-tilt

Steps to reproduce

  1. Create new TypeScript project
  2. Install react-parallax-tilt
  3. Import Tilt from react-parallax-tilt

Expected behavior

Types to be declared.

Code snippets

No response

React Parallax Tilt Version

1.7.16

Browser

No response

Operating System

  • macOS
  • Windows
  • Linux

Additional Information

No response

Only one Tilt works at a time

๐Ÿ› Issue/Bug Report Template

Describe the bug
Multiple Tilts won't work at the same time. Only the most recently instanced will work.

To Reproduce
See my CSB here: https://codesandbox.io/s/parallax-tests-h584m

Expected behavior
Both elements on the screen are configured identically other than image and text. They should behave the same.

  • Browser:
  • Version: "react-parallax-tilt":
  • ...

Unable to use on node v17/v18

Description

Installing this library on node versions greater than 16 produces the following error:

The engine "node" is incompatible with this module. Expected version "16.x".

Id love to integrate this library in my app, but this is preventing that.

Link to Reproduction

n/a

Steps to reproduce

No response

Expected behavior

Install

Code snippets

No response

React Parallax Tilt Version

1.7.58

Browser

No response

Operating System

  • macOS
  • Windows
  • Linux

Additional Information

No response

Component dropping effects after animating in

๐Ÿ› Component dropping effects after animating in

After animating a Tilt component in based on X or Y values, the X and Y axis for the tilt component seems to be locked and reversed in a way.

I've made a test sandbox here:
https://codesandbox.io/s/tender-pasteur-f9lmc

Expected behavior
There's 3 tilt components labelled. The middle component labelled 'without motion' should be the effect for the 'with motion', but theres some strange behaviour going on. There's no issue when you add the event to the whole window though, so it is most likely something to do with the animating I believe. All the components have the same props and everything too.

Environment

  • Browser: Chrome / Mac
  • Version: "react-parallax-tilt": 1.4.70

โค๏ธ this package btw!
TIA

Uncaught runtime errors

Description

Cannot read properties of null (reading 'style')
TypeError: Cannot read properties of null (reading 'style')

Link to Reproduction - Please provide demo in online code editor CodeSandbox or similar. - Issues without a reproduction link are likely to stall.

no

Steps to reproduce

  1. Go to '...'
  2. Click on '...'
  3. Scroll down to '...'
  4. See error

Expected behavior

click

Code snippets

<Tilt reset={false}>
  <MyComponent />
</Tilt>

React Parallax Tilt Version

1.7.163

Browser

No response

Operating System

  • macOS
  • Windows
  • Linux

Additional Information

No response

Doesn't support rounded edges (or other glare props)

๐Ÿ› Issue/Bug Report Template

Describe the bug
If using rounded edges for the component and there is a dark background, the tilt component doesn't honour the rounded edges.

To Reproduce
Steps to reproduce the behavior:

Exactly as in the Glare demo here: https://mkosir.github.io/react-parallax-tilt/?path=/story/react-parallax-tilt--glare-effect, but with a dark background.

import React from 'react';

import Tilt from '../../src';
import DefaultComponent from '../_DefaultComponent/DefaultComponent';

const GlareEffect = () => (
  <Tilt glareEnable={true} glareMaxOpacity={0.8} glareColor="#ffffff" glarePosition="bottom">
    <div style={{ background: black }}>
      <DefaultComponent />
    </div>
  </Tilt>
);

export default GlareEffect;

Expected behavior
It would be nice to be able to pass props down to the Glare Element (unless this is already possible and not clearly documented?). Or do you suggest just using CSS to override the glare-wrapper class?

Link to demo (required)
https://codesandbox.io/s/recursing-perlman-c09t3?fontsize=14&hidenavigation=1&theme=dark

Issues without a reproduction link are likely to stall.

Code snippets
As above or Codesandbox link.

Environment

  • Browser: Chrome
  • Version: "react-parallax-tilt":
  • ...

Additional context
Add any other context about the problem here.

Don't log Device Orientation as an error

๐Ÿ› Issue/Bug Report Template

Describe the bug
When devices don't support gyroscope/device orientation, there's an error in the console. It'd be nice to try/catch this and instead log a warning.

To Reproduce
Steps to reproduce the behavior:

  1. Launch a parallax site with gyroscope enabled
  2. Open developer console
  3. See error

Expected behavior
Instead of logging an error, log as a warning in development mode (and maybe don't log anything in production?)

Link to demo (highly encouraged)

Code snippets
If applicable, add code samples to help explain your problem.

Environment

  • Browser: Safari 14.0 (16610.1.15.51.2) on macOS Big Sur (10.16; not Apple Silicon)
  • Version: "react-parallax-tilt": 1.4.56

Additional context
n/a

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.