Code Monkey home page Code Monkey logo

lottie-react's Introduction

LottiePlayer React Component

This is a React component for the Lottie Web Player

Demo

screencast

Documentation

In Javascript or TypeScript:

  1. Install package using npm or yarn.
npm install --save @lottiefiles/react-lottie-player
  1. Import package in your code.
import { Player, Controls } from '@lottiefiles/react-lottie-player';

Example/Development

  1. Clone repo

  2. run yarn install

  3. run yarn storybook

yarn storybook

Usage

Player component

Add the element Player and set the src prop to a URL pointing to a valid Lottie JSON.

<Player
  autoplay
  loop
  src="https://assets3.lottiefiles.com/packages/lf20_UJNc2t.json"
  style={{ height: '300px', width: '300px' }}
>
  <Controls visible={true} buttons={['play', 'repeat', 'frame', 'debug']} />
</Player>

Props

Prop Description Type Default
lottieRef Get lottie animation object function undefined
onEvent Listen for events function undefined
onStateChange Play state changes function undefined
onBackgroundChange Listen for bg changes function undefined
autoplay Autoplay animation on load. boolean false
background Background color. string undefined
controls Show controls. boolean false
direction Direction of animation. number 1
hover Whether to play on mouse hover. boolean false
keepLastFrame Stop animation on the last frame.
Has no effect if loop is true.
boolean false
loop Whether to loop animation. boolean false
renderer Renderer to use. `"svg" "canvas"`
speed Animation speed. number 1
style The style for the container. object undefined
src (required) Bodymovin JSON data or URL to JSON. object string

Get Player instance

To call methods on the instance of the Player component. you may get a reference to the component and call the methods on ref.current. This is esentially reacts way of doing a document.getElementById(); You may then use this ref ie: player in the example below to call methods that are described in this documentation. See ref in react documentation

import React from 'react';
import { Player } from '@lottiefiles/react-lottie-player';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.player = React.createRef(); // initialize your ref
  }
  render() {
    return (
      <Player
        ref={this.player} // set the ref to your class instance
        autoplay={false}
        loop={true}
        controls={true}
        src="https://assets3.lottiefiles.com/packages/lf20_XZ3pkn.json"
        style={{ height: '300px', width: '300px' }}
      ></Player>
    );
  }
}

export default App;

Get Lottie instance

The lottieRef prop returns the Lottie instance which you can use to set data and call methods as described in the bodymovin documentation.

import React from 'react';
import { Player } from '@lottiefiles/react-lottie-player';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { lottie: null }; // initialize your state
  }

  render() {
    return (
      <Player
        lottieRef={instance => {
          this.setState({ lottie: instance }); // the lottie instance is returned in the argument of this prop. set it to your local state
        }}
        autoplay={false}
        loop={true}
        controls={true}
        src="https://assets3.lottiefiles.com/packages/lf20_XZ3pkn.json"
        style={{ height: '300px', width: '300px' }}
      ></Player>
    );
  }
}

export default App;

Listening for events

import React from 'react';
import { Player } from '@lottiefiles/react-lottie-player';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.player = React.createRef();
  }

  doSomething() {
    this.player.current.play(); // make use of the player and call methods
  }

  render() {
    return (
      <Player
        onEvent={event => {
          if (event === 'load') this.doSomething(); // check event type and do something
        }}
        ref={this.player}
        autoplay={false}
        loop={true}
        controls={true}
        src="https://assets3.lottiefiles.com/packages/lf20_XZ3pkn.json"
        style={{ height: '300px', width: '300px' }}
      ></Player>
    );
  }
}

export default App;

Events

The following events are exposed and can be listened to via addEventListener calls.

Name Description
load Animation data is loaded.
error An animation source cannot be parsed, fails to load or has format errors.
ready Animation data is loaded and player is ready.
play Animation starts playing.
pause Animation is paused.
stop Animation is stopped.
freeze Animation is paused due to player being invisible.
loop An animation loop is completed.
complete Animation is complete (all loops completed).
frame A new frame is entered.

Methods

pause() => void

Pause animation play.

Returns

Type: void

play() => void

Start playing animation.

Returns

Type: void

setPlayerDirection(direction: 1 | -1 ) => void

Animation play direction.

Parameters

Name Type Description
value number Direction values.

Returns

Type: void

setPlayerSpeed(speed?: number) => void

Sets animation play speed.

Parameters

Name Type Description
value number Playback speed.

Returns

Type: void

stop() => void

Stops animation play.

Returns

Type: void

setSeeker(frame: number, play: boolean) => void

Seek to a given frame.

Returns

Type: void

Contributing

We use changesets to maintain a changelog for this repository. When making any change to the codebase that impacts functionality or performance we require a changeset to be present.

To add a changeset run:

yarn run changeset

And select the type of version bump you'd like (major, minor, path).

You can document the change in detail and format it properly using Markdown by opening the ".md" file that the "yarn changeset" command created in the ".changeset" folder. Open the file, it should look something like this:

---
"@lottiefiles/pkg1": minor
"@lottiefiles/pkg2": major
---

This is where you document your **changes** using Markdown.

- You can write
- However you'd like
- In as much detail as you'd like

Aim to provide enough details so that team mates and future you can understand the changes and the context of the change.

You can commit your changes and the changeset to your branch and then create a pull request on the develop branch.

License

MIT License Β© LottieFiles.com

lottie-react's People

Contributors

jaulz avatar jawish avatar karamalie avatar lbaron-ut avatar lottiefiles-bot avatar lucienlee avatar samuelosborne avatar soare-robert-daniel avatar sorosora avatar stwiname avatar theashraf avatar yunyong 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

lottie-react's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Support for React 16.8.0+ ?

npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^16.13.1" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^17.0.2" from @lottiefiles/[email protected]
npm ERR! node_modules/@lottiefiles/react-lottie-player
npm ERR!   @lottiefiles/react-lottie-player@"*" from the root project

styles override

hello,

can u please added a prefix to all styles in my project override styles for example :

.progress
.popover

to

lt-progress
lt-popover

thanks

Support for preserveAspectRatio

Overview

The @lottiefiles/lottie-player supports the preserveAspectRatio property which is handy to cover the entire page with animation. I thought it'd be helpful if the property is also supported for the React version.

...

Motivation

What inspired this enhancement? What makes you think this should be included?

It would be great to be able to pass in preserveAspectRatio so I can use the React version of the library.

...

Labels

  • Add the Type: Enhancement label to this issue.

Any way to set preserveAspectRatio?

preserveAspectRatio on the svg seems to default to xMidyMid meet and there doesn't seem to be any way to change it. (Or at least i can't find any way). Could a way to set it be added?

Add ariaLabel prop to support ADA

Overview

To support ADA-related concerns, add an ariaLabel prop (or similar) which would add an aria-label attribute on the "parent" div, (the div which currently has the id attribute).

Type

  • New feature
  • Changes to existing features

Motivation

Update lottie-react library to be more ADA compliant.

...

Labels

  • Add the Type: Feature Request label to this issue.

keepLastFrame behaviour

Hi, I'm setting keepLastFrame to true so that my animation stays on the last frame when it's done playing. This isn't working and instead the animation reverts back to frame 0. Is this a bug or have I misunderstood the expected behaviour of keepLastFrame?

Using imported JSON file as source only works when spreading into new object

Overview

When using an imported lottie JSON file as the src rather than specifying a URL, I have to spread the JSON object into a new object every time the component renders, otherwise the animation doesnt play. I'm not sure if there's a valid reason for it or it's a bug.

This doesnt work - the animation doesnt play:

import AnimationData from "./animation.json";
//...
<Player src={AnimationData} ... />

But this does work - the animation plays

import AnimationData from "./animation.json";
//...
<Player src={{...AnimationData}} ... />

Consuming repo

What repo were you working in when this issue occurred?

I've reproduced this in a couple of repos, including this codesandbox.

Labels

  • Add the Type: Bug label to this issue.

Consider attaching `className` to the outer-most container

Currently, even though the Player accepts a className prop, it is not passed to the outer-most container of the animation. So the render tree will always be .lf-player-container > #lottie and only #lottie can be styled via className. This creates some issues when you need to style the most direct container of your views for layout purposes etc. Solutions that I would consider for this issue:

  1. Attach className to .lf-player-container instead
  2. Remove .lf-player-container altogether and make #lottie the direct container
  3. Add some additional prop that allows styling .lf-player-container.

At the moment the only way to style the .lf-player-container is to use some direct descendant selector or use the class name directly, but then we need to leak internal implementation of the library into our codebase which we consider a bad practice.

Thanks for considering and thanks for the great library! :)

React warning in console when passing `lottieRef` to `Player` component

Hi, I'm using the LottiePlayer component like so:

import type { AnimationItem } from 'lottie-web';
import { Player } from '@lottiefiles/react-lottie-player';
...
const lottieRef = useRef<AnimationItem>();
...
<Player
    lottieRef={(ref) => {
        lottieRef.current = ref;
    }}
    loop
    src="..."
/>

Everything works perfectly, except I'm getting the following error in the chrome dev tools console:

image

Is there any way I can get rid of that warning ?
Thanks!

Error event doesn't work

Overview

I would like to check if there's been an error with the animation but I'm currently unable. I've been trying it through the prop onEvent and even though I source a failed .json file I don't receive an error.

Here's what I'm trying to do:

onEvent={(event) => {
        if (event === 'error') doSomenthing()
      }}

Any idea on how to verify that? Thank you!

Consuming repo

What repo were you working in when this issue occurred?

...

Labels

  • Add the Type: Bug label to this issue.

Support to provide animationData ?

Overview

...

Motivation

What inspired this enhancement? What makes you think this should be included?

...

Labels

  • Add the Type: Enhancement label to this issue.

Warning because of types not correctly mapped

Hello

When I start my server or build my project using CRA v5 I have these messages:

WARNING in ./node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/node_modules/@lottiefiles/react-lottie-player/src/Seeker.tsx' 
file: Error: ENOENT: no such file or directory, open '/node_modules/@lottiefiles/react-lottie-player/src/Seeker.tsx'

In fact types are located in /node_modules/@lottiefiles/react-lottie-player/dist/src but it seems that the lottie-react.esm.js.map says:

{"version":3,"file":"lottie-react.esm.js","sources":["../src/Player.tsx","../node_modules/style-inject/dist/style-inject.es.js","../src/ColorPicker.tsx","../src/Popover.tsx","../src/Seeker.tsx","../src/Controls.tsx"] ...}

The source map file is pointing to ../src instead of /src.

I don't really know if it's a config issue on my side or the package was badly built and published on npm.

Thanks a lot for your help

Speed is overriden

Tell us about your environment

  • Browser and Browser Version:
    chrome 98

What did you do? Please explain the steps you took before you encountered the problem.

I have more than one lottie icon on a given page. it seems that the last one to load is setting the speed for all of them. I have one with speed="0.5" and 2 with a speed="2" and it seems that all of them behave at a speed of 2.

What did you expect to happen?

I would expect each lottie component to be independent.

I tried to edit the labels but i don't think i have the rights to do it.

Learning the instant frame

Hello, I want to play an animation only between certain frames and I could not find a document about it. I just found the function named setSeeker. I can start it in certain frame, but how do I stop it?

[Feature request] keepLastFrame

Hello, I don't know if this is already possible using other API's (if yes, can you show me how?), but I would suggest 2 solutions

1 New keepLastFrame property

When the animation is not looping (loop={false}), when keepLastFrame property is true, the player should keep the last animation frame. This is particularly useful when playing entrance animations and the elements should stay in their final position when the animation ends.

lottie-react/src/Player.tsx

Lines 252 to 255 in 8564a38

newInstance.addEventListener('complete', () => {
this.setState({ playerState: PlayerState.Paused });
this.setSeeker(0);
});

This can become:

newInstance.addEventListener('complete', () => {
     this.setState({ playerState: PlayerState.Paused });
     (!loop & keepLastFrame) ? this.setSeeker(0) : this.setSeeker(100);  // Dunno the real number here
});

2 Prevent frames reset

If you don't want to make this optional, I would suggest removing this.setSeeker(0) and prevent the frames reset (like the standard HTML player)

Leaking/performance issues when adding/removing from tree

Overview

If the Player is added/removed from the tree, something internally is leaking and it can cause the animation to jank and then the page to crash.

See this sandbox: https://codesandbox.io/s/confident-booth-unplv?file=/src/App.tsx

Click the toggle button once. Everything works and the animation shows. Click it twice and it might be a bit slower. 3-4+ times (at least on my computer) it slows to a crawl and the page becomes unresponsive.

Labels

  • Add the Type: Bug label to this issue.

Slow loading

Overview

I've noticed that the loading speed of the animations is very slow, which i assume is because of the .json endpoint. Is it possible to download the .json and use it within our project so it loads instantly?

Consuming repo

What repo were you working in when this issue occurred?
lottie-react
...

Labels

  • [Bug ] Add the Type: Bug label to this issue.

Support for React 17?

Found: [email protected]
node_modules/react
react@"^17.0.1" from the root project

Could not resolve dependency:
peer react@"^16.8.6" from @lottiefiles/[email protected]
node_modules/@lottiefiles/react-lottie-player
@lottiefiles/react-lottie-player@"^3.0.0" from the root project

Remaining prop support from the lottie web player

Overview

Can you add the following props to be available as seen on the main lottie player package?

  • description?: string = 'Lottie animation';
  • intermission?: number = 1;
  • mode?: 'normal' | 'bounce' = 'normal';

Type

  • New feature
  • Changes to existing features

Motivation

What inspired this feature request? What problems were you facing, or what else makes you think this should be
included?

Just wanting to be able to support all the features from Lottie while still using this react package.

Labels

  • Add the Type: Feature Request label to this issue.

A couple of typescript issues with the most recent release

I just upgraded react-lottie-player in my typescript project and I found that I have to specify the type for styles now - IPlayerProps['style'] or my app fails to compile, as it doesn't like the type for position: 'absolute'

const spinnerStyles: IPlayerProps['style'] = {
  height: '2.1rem',
  width: '2.1rem',
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)'
};

<Player
      autoplay
      loop
      renderer='svg'
      src={spinnerJson}
      style={spinnerStyles}
    />
    

With that type added, everything runs correctly, but in the console I get a warning:

Warning: Invalid DOM property `autoplay`. Did you mean `autoPlay`?

complete event doesn't work

It seems that the complete event is not working/throw. Taking this example:

import React from 'react';
import { Player } from '@lottiefiles/react-lottie-player';
 
class App extends React.Component {
  constructor(props) {
    super(props);
    this.player = React.createRef();
  }
 
  render() {
    return (
      <Player
        onEvent={event => {
          if (event === 'complete') console.log('Finished'); 
        }}
        ref={this.player}
        autoplay={false}
        loop={false}
        controls={true}
        src="https://assets3.lottiefiles.com/packages/lf20_XZ3pkn.json"
      ></Player>
    );
  }
}
 
export default App;

There isn't any complete event, but logging the event, I see only load, play, and frame events.

Digging the code, it seems that no event is triggered inside the complete listener:

lottie-react/src/Player.tsx

Lines 252 to 255 in 8564a38

newInstance.addEventListener('complete', () => {
this.setState({ playerState: PlayerState.Paused });
this.setSeeker(0);
});

There should be a this.triggerEvent(PlayerEvent.Complete);

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Support for React 18

Overview

Currently the library only supports react "^17.0.2".

  • Will the library easily work with react 18?
  • If yes, could we allow this version in the peer dependencies?
  • If no, is there a plan and ETA to have this library work with react 18?

Other naive question, do we need a peer dependency on react for this library?

Linked to #77 (comment)

Thanks a lot!

Motivation

What inspired this enhancement? What makes you think this should be included?

Would be great to be able to use this library with the latest supported react version

Labels

  • Add the Type: Enhancement label to this issue. ➑️ Unable to add a label sorry

Component pollutes global styles

Using the player in my site, I noticed that it pollutes the styles of the whole page. E.g. it set's styles for .btn, setting the width to 14px so now all buttons on my site want to be only 14px wide.

Toggle is not working

i can't found how can i do toggle. I tried that way but not working.

export default function Home() {
  const ref = createRef();
  const [isSelected, setIsSelected] = useState(false);

  const handleClick = () => {
    if (isSelected) {
      ref.current.play(0, 30);
    } else {
      ref.current.play(30, 0);
    }
    setIsSelected(!isSelected);
  };

  return (
    <div>
      <button onClick={handleClick}>
        <Player
          ref={ref}
          src="/lottie/star.json"
          style={{ height: "40px", width: "40px" }}
        />
      </button>
    </div>
  );
}

Cannot read error of null

Hello, I have a very simple lottie player componnent that sometime stop and throw an error on component mount / unmount

const LoaderIcon = ({ size = '1.5rem' }: { size?: string }) => (
	<Player
		autoplay
		style={{ height: size, width: size }}
		loop
		src="https://assets5.lottiefiles.com/private_files/lf30_tjqo85qt.json"
	>
		<Controls visible={false} buttons={['play', 'repeat', 'frame', 'debug']} />
	</Player>
)
lottie-react.esm.js:1 Uncaught TypeError: Cannot read property 'error' of null
    at AnimationItem.triggerEvent (lottie-react.esm.js:1)
    at AnimationItem../node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js.AnimationItem.triggerRenderFrameError (lottie-react.esm.js:9)
    at AnimationItem../node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js.AnimationItem.renderFrame (lottie-react.esm.js:9)
    at AnimationItem../node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js.AnimationItem.gotoFrame (lottie-react.esm.js:9)
    at AnimationItem../node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js.AnimationItem.setCurrentRawFrameValue (lottie-react.esm.js:9)
    at AnimationItem../node_modules/@lottiefiles/react-lottie-player/dist/lottie-react.esm.js.AnimationItem.advanceTime (lottie-react.esm.js:9)
    at f (lottie-react.esm.js:9)

[Feature Request] Change `style` type to `React.CSSProperties`

Overview

What do you think about changing style?: { [key: string]: string | number; }; to style?: React.CSSProperties?

Type

  • New feature
  • Changes to existing features

Motivation

What inspired this feature request? What problems were you facing, or what else makes you think this should be
included?

For example with CSSProperties will be better IDE support etc.

Labels

  • Add the Type: Feature Request label to this issue.

Inputs (eg. text, checkbox) lose their browser default focus styling

If I import the player onto a page with inputs, the default blue outline that Chrome adds when focusing on an input element no longer appears.

import { Player } from "@lottiefiles/react-lottie-player";
export default () => <input type='text'/>

In the above example their will be no outline on focus. If you comment out the import the focus outline will return.

It appears to be caused by this CSS with a very generic selector:
https://github.com/LottieFiles/lottie-react/blob/master/src/Styles.css#L74

Warning when I use React Routes

I am using React Routes, and when I change of page where I have a Player component I get this warning in console.

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

It's probably that you have an asynchronous function running and when I change the path with React Routes the Player component is unmounted but the asynchronous function is not cancelled

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.