GithubHelp home page GithubHelp logo

thedevelobear / react-rewards Goto Github PK

View Code? Open in Web Editor NEW
1.5K 5.0 52.0 5.25 MB

A package containing a few micro-interactions you can use to reward your users for little things and make them smile!

Home Page: https://github.com/thedevelobear/react-rewards

License: MIT License

JavaScript 4.40% TypeScript 95.60%
front-end react reactjs react-components rewards ux user-experience confetti emoji balloons

react-rewards's Introduction

react-rewards logo

npm version forthebadge

🌲 Tree-shakeable πŸ•΅οΈβ€β™€οΈ Built with TypeScript πŸ“¦ 3.6kB gzipped

This package was inspired by react-dom-confetti.

React-rewards lets you add micro-interactions to your app, and rewards users with the rain of confetti, emoji or balloons in seconds. Firing confetti all over the page may seem like a questionable idea, but keep in mind that rewarding users for their actions is not. If a huge cloud of smiling emoji doesn't fit your application well, try changing the physics config to make it more subtle.

You can read more on the subject of micro-interactions in my blog post – https://www.thedevelobear.com/post/microinteractions/

Confetti

confetti demo gif

Balloons

balloons demo gif

Emoji

emoji demo gif

Installation

Install from npm by typing npm install react-rewards or yarn add react-rewards while in your package.json directory.

Usage

In order to use the rewards, you'll need to provide an element that will become the origin of the animation. This element needs to have an ID that matches the one used inside the hook - it can be anywhere in the DOM as long as the IDs match.

You can place the element inside a button, center it and shoot up from the button. You can place it on top of the viewport with position: "fixed" and change the angle to 270, to shoot downwards. Try, experiment, have fun!

Animation particles are set to position: 'fixed' by default, but this can be changed through a config object.

Single reward

TIP: Try using <span id=β€œrewardId” style={{width: 2, height: 2, background: β€œred”}} /> to place the element correctly, wherever you want. Then just remove the styles.

import { useReward } from 'react-rewards';
...
const { reward, isAnimating } = useReward('rewardId', 'confetti');
...
<button
    disabled={isAnimating}
    onClick={reward}
>
    <span id="rewardId" />
    πŸŽ‰
</button>

Multiple rewards

TIP: You can use the same ID to shoot from the same spot, or provide separate elements with unique IDs.

import { useReward } from 'react-rewards';
...
const {reward: confettiReward, isAnimating: isConfettiAnimating} = useReward('confettiReward', 'confetti');
const {reward: balloonsReward, isAnimating: isBalloonsAnimating} = useReward('balloonsReward', 'balloons');
...
<button
    disabled={isConfettiAnimating || isBalloonsAnimating}
    onClick={() => {
        confettiReward();
        balloonsReward();
    }}
>
    <span id="confettiReward" />
    <span id="balloonsReward" />
    πŸŽ‰
</button>

Props & config

useReward params:

name type description required default
id string A unique id of the element you want to shoot from yes
type string 'confetti' 'balloons' 'emoji'
config object a configuration object described below no see below

Confetti config object:

name type description default
lifetime number time of life 200
angle number initial direction of particles in degrees 90
decay number how much the velocity decreases with each frame 0.94
spread number spread of particles in degrees 45
startVelocity number initial velocity of particles 35
elementCount number particles quantity 50
elementSize number particle size in px 8
zIndex number z-index of particles 0
position string one of CSSProperties['position'] - e.g. "absolute" "fixed"
colors string[] An array of colors used when generating confetti ['#A45BF1', '#25C6F6', '#72F753', '#F76C88', '#F5F770']
onAnimationComplete () => void A function that runs when animation completes undefined

Balloons config object:

name type description default
lifetime number time of life 600
angle number initial direction of balloons in degrees 90
decay number how much the velocity decreases with each frame 0.999
spread number spread of balloons in degrees 50
startVelocity number initial velocity of the balloons 3
elementCount number balloons quantity 10
elementSize number balloons size in px 20
zIndex number z-index of balloons 0
position string one of CSSProperties['position'] - e.g. "absolute" "fixed"
colors string[] An array of colors used when generating balloons ['#A45BF1', '#25C6F6', '#72F753', '#F76C88', '#F5F770']
onAnimationComplete () => void A function that runs when animation completes undefined

Emoji config object:

name type description default
lifetime number time of life 200
angle number initial direction of emoji in degrees 90
decay number how much the velocity decreases with each frame 0.94
spread number spread of emoji in degrees 45
startVelocity number initial velocity of emoji 35
elementCount number emoji quantity 20
elementSize number emoji size in px 25
zIndex number z-index of emoji 0
position string one of CSSProperties['position'] - e.g. "absolute" "fixed"
emoji string[] An array of emoji to shoot ['πŸ€“', '😊', 'πŸ₯³']
onAnimationComplete () => void A function that runs when animation completes undefined

react-rewards's People

Contributors

campbellmg avatar compscikai avatar dependabot[bot] avatar drplauska avatar enu-kuro avatar jacekk avatar lehasvv2009 avatar marvinschopf avatar thedevelobear 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

react-rewards's Issues

Canvas Null Issue

Using this in React. All works well locally but when pushed to production the following error is thrown: TypeError: Cannot set property 'fillStyle' of null

How can I go about resolving this canvas related issue?

IE 11 support?

The neutrino build setup doesn't compile down arrow functions which breaks for IE11.
Just wondering if you would consider using a more compatible build preset?

Npm vulnerabilities warnings

react-rewards looks really cool, but I'm getting this when installing:

Before adding react-rewards:

audited 7230 packages in 7.906s
found 0 vulnerabilities

After:

audited 140631 packages in 26.794s
found 17 vulnerabilities (14 moderate, 3 high)

All of these stem from neutrino related packages. Should neutrino really be part of what's published on npm? I'm guessing you are using for the demo page.

Memoize `reward`

Awesome library, love it!

However, the following code doesn't work as one would expect (it keeps rewarding me over and over):

useEffect(() => {
	if (step === 1) {
		reward();
	}
}, [step, reward]);

Seems like reward() would benefit from being memoized with useCallback.

how to add custom emoji

Hello,
thanks for the nice package.
how to add custom emoji? it might be helpful add an example to the document.

i tried like below. is this the right way?

import { useReward } from 'react-rewards';
...
const { reward: confettiReward, isAnimating } = useReward(
    "rewardId",
    "emoji",
    {
      emoji: ["⚑️", "πŸ’₯", "✨", "πŸ’«", "🌸", "🌟"],
    }
  );
...
<button
    disabled={isConfettiAnimating}
    onClick={() => {
        confettiReward();
    }}
>
    <span id="confettiReward" />
    πŸŽ‰
</button>

Wow, that's fast!

Hey,

I use this package already for a long time, but in the meantime the animation speed increased. It's like it spead up to double so fast or even more. I thought about the config parameter "lifetime", but that just changes the lifetime not the animation speed lol.

This is my code:

           <Reward
                ref={ref}
                type='emoji'
                config={{
                    elementCount: 12,
                    angle: 80,
                    springAnimation: false,
                    emoji: rewardEmojis
                }}
            >
... some other Components...
            </Reward>

I call the methods like that box.target.checked ? ref.current.rewardMe() : ref.current.punishMe();

Well, am I missing something or do something wrong? How can I make the animation slower?
Look how fast

Is it possible to launch an effect on page load..?

Hi all, I'm trying to run confetti on page load after a user pays for a product successfully. As such, I need to run the reward as soon as the payment confirmation page loads.

I wasn't able to get this to work with useEffect. Is this only possible via an onClick event?

feature request: emoji-balloon

It would be useful to have a balloon variant of the emoji reward, use case would be to use ['❀️', '🩷'] as a heart balloon.

Thanks!

useReward can't find element if it's rendered conditionally

I'm aware of this issue and I'll fix it in the upcoming release. Here's an example of the code that doesn't work at the moment:


const SomeAsyncScreen = () => {
  const [ data, setData ] = useState(undefined);
  const { reward, isAnimating } = useReward("rewardId", "confetti");

  useEffect(() => {
    setTimeout(() => {
      setData({});
    }, 500);
  }, []);

  if (!data) return "Loading...";

  return (
    <div className="App">
      <span id="rewardId" /> 
      <button disabled={isAnimating} onClick={reward}>
        Make it rain!
      </button>
    </div>
  );
};

The problem is that the element is grabbed in useLayoutEffect, which fires synchronously after all DOM mutations. In this case there's no element with an id === "rewardId" on mount.

While I'm working on that, a possible solution would be to bring the target element one level up, or always render the element and make other parts of the screen conditional, like so:


const SomeAsyncScreen = () => {
  const [ data, setData ] = useState(undefined);
  const { reward, isAnimating } = useReward("rewardId", "confetti");

  useEffect(() => {
    setTimeout(() => {
      setData({});
    }, 500);
  }, []);

  return (
    <div className="App">
      <span id="rewardId" /> 
      {data && <SomeDataDependentJsx/>} 
      <button disabled={isAnimating} onClick={reward}>
        Make it rain!
      </button>
    </div>
  );
};

First of all NICE PACKAGE!

Can I explode twitter emojis? Currently, I've just found a way to explode only native emojis. I want to explode same emoji graphics on every device. And how do I change the position of which explosion will happen?

Once again, NICE PACKAGE!
Thanks!

Confeitti Stickers are flowing back side of the DIV Elements

Its a wonderful NPM. Working like a charm. I have one issue. After triggering react-rewards in confeitti mode, my stickers flowing back side of the DIV elements. So I cant able to see the stickers properly. My Expectation is it should come infront all other elements. Any suggestions?

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.