All Projects β†’ szhsin β†’ react-transition-state

szhsin / react-transition-state

Licence: MIT license
Zero dependency React transition state machine.

Programming Languages

javascript
184084 projects - #8 most used programming language
CSS
56736 projects
HTML
75241 projects
shell
77523 projects

Projects that are alternatives of or similar to react-transition-state

react-gizmo
🦎 React Gizmo - UI Finite State Machine for React
Stars: ✭ 39 (-83.68%)
Mutual labels:  state-machine, transition
use-spring
Hooke's law hook
Stars: ✭ 53 (-77.82%)
Mutual labels:  hook, transition
Stately.js
Stately.js is a JavaScript based finite-state machine (FSM) engine for Node.js and the browser.
Stars: ✭ 785 (+228.45%)
Mutual labels:  state-machine, transition
FiniteStateMachine
This project is a finite state machine designed to be used in games.
Stars: ✭ 45 (-81.17%)
Mutual labels:  state-machine, transition
Aasm
AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid, NoBrainer, Dynamoid)
Stars: ✭ 4,474 (+1771.97%)
Mutual labels:  state-machine, transition
Laravel Stager
Laravel Stager State Machine, Its purpose is to add state machine functionality to models
Stars: ✭ 16 (-93.31%)
Mutual labels:  state-machine, transition
Use Web Animations
😎 🍿 React hook for highly-performant and manipulable animations using Web Animations API.
Stars: ✭ 802 (+235.56%)
Mutual labels:  hook, transition
jazzer
Add some visual smooth jazz to your page
Stars: ✭ 19 (-92.05%)
Mutual labels:  transition
preact-transitioning
Preact components for easily implementing basic CSS animations and transitions
Stars: ✭ 35 (-85.36%)
Mutual labels:  transition
SwiftElm
Reactive + Automaton + VTree in Swift, inspired by Elm.
Stars: ✭ 97 (-59.41%)
Mutual labels:  state-machine
Text101-Original
A basic state-machine based text adventure exercise as part of our Complete Unity C# Developer course (http://gdev.tv/cudgithub)
Stars: ✭ 43 (-82.01%)
Mutual labels:  state-machine
Ryder
Runtime redirection of method calls for .NET Core.
Stars: ✭ 34 (-85.77%)
Mutual labels:  hook
use-route-as-state
Use React Router route and query string as component state
Stars: ✭ 37 (-84.52%)
Mutual labels:  hook
react-media-hook
React Hook for Media Queries
Stars: ✭ 60 (-74.9%)
Mutual labels:  hook
Interface-Inspector-Hook
Interface Inspector破解
Stars: ✭ 43 (-82.01%)
Mutual labels:  hook
react-use-countdown
React hook for countdown state.
Stars: ✭ 19 (-92.05%)
Mutual labels:  hook
xoid
Framework-agnostic state management library designed for simplicity and scalability βš›
Stars: ✭ 96 (-59.83%)
Mutual labels:  state-machine
react-router-v4-transition
React Router V4 Transition
Stars: ✭ 40 (-83.26%)
Mutual labels:  transition
minimal-player
This is a minimal, clean audio/music/mp3 player with spinning cover images, built with jQuery, TweenMax.js and SVG images.
Stars: ✭ 48 (-79.92%)
Mutual labels:  transition
LollipopTransition
ε…³δΊŽε…±δΊ«ε…ƒη΄ δΈŽtransitionζ‘†ζžΆηš„ε­¦δΉ 
Stars: ✭ 30 (-87.45%)
Mutual labels:  transition

React-Transition-State

NPM NPM NPM Known Vulnerabilities

Features

Inspired by the React Transition Group, this tiny library helps you easily perform animations/transitions of your React component in a fully controlled manner, using a Hook API.

  • 🍭 Working with both CSS animation and transition.
  • πŸ”„ Moving React components in and out of DOM seamlessly.
  • 🚫 Using no derived state.
  • πŸš€ Efficient: each state transition results in at most one extract render for consuming component.
  • 🀏 Tiny: ~1KB(post-treeshaking) and no dependencies, ideal for both component libraries and applications.

πŸ€” Not convinced? See a comparison with React Transition Group


State diagram

state-diagram The initialEntered and mountOnEnter props are omitted from the diagram to keep it less convoluted. Please read more details at the API section.


Install

# with npm
npm install react-transition-state

# with Yarn
yarn add react-transition-state

Usage

CSS example

import { useTransition } from 'react-transition-state';
/* or import useTransition from 'react-transition-state'; */

function Example() {
  const [state, toggle] = useTransition({ timeout: 750, preEnter: true });
  return (
    <div>
      <button onClick={() => toggle()}>toggle</button>
      <div className={`example ${state.status}`}>React transition state</div>
    </div>
  );
}

export default Example;
.example {
  transition: all 0.75s;
}

.example.preEnter,
.example.exiting {
  opacity: 0;
  transform: scale(0.5);
}

.example.exited {
  display: none;
}

Edit on CodeSandbox


styled-components example

import styled from 'styled-components';
import { useTransition } from 'react-transition-state';

const Box = styled.div`
  transition: all 500ms;

  ${({ status }) =>
    (status === 'preEnter' || status === 'exiting') &&
    `
      opacity: 0;
      transform: scale(0.9);
    `}
`;

function StyledExample() {
  const [{ status, isMounted }, toggle] = useTransition({
    timeout: 500,
    mountOnEnter: true,
    unmountOnExit: true,
    preEnter: true
  });

  return (
    <div>
      {!isMounted && <button onClick={() => toggle(true)}>Show Message</button>}
      {isMounted && (
        <Box status={status}>
          <p>This message is being transitioned in and out of the DOM.</p>
          <button onClick={() => toggle(false)}>Close</button>
        </Box>
      )}
    </div>
  );
}

export default StyledExample;

Edit on CodeSandbox


tailwindcss example

Edit on CodeSandbox


Perform appearing transition when page loads or a component mounts

You can toggle on transition with the useEffect hook.

useEffect(() => {
  toggle(true);
}, [toggle]);

Edit on CodeSandbox


Comparisons with React Transition Group

React Transition Group This library
Use derived state Yes – use an in prop to trigger changes in a derived transition state No – there is only a single state which is triggered by a toggle function
Controlled No –
Transition state is managed internally.
Resort to callback events to read the internal state.
Yes –
Transition state is lifted up into the consuming component.
You have direct access to the transition state.
DOM updates Imperative – commit changes into DOM imperatively to update classes Declarative – you declare what the classes look like and DOM updates are taken care of by ReactDOM
Render something in response to state updates Resort to side effects – rendering based on state update events Pure – rendering based on transition state
Working with styled-components Your code looks like –
&.box-exit-active { opacity: 0; }
&.box-enter-active { opacity: 1; }
Your code looks like –
opacity: ${({ state }) => (state === 'exiting' ? '0' : '1')};
It's the way how you normally use the styled-components
Bundle size NPM βœ… NPM
Dependency count NPM βœ… NPM

This CodeSandbox example demonstrates how the same transition can be implemented in a simpler, more declarative, and controllable manner than React Transition Group.


API

useTransition Hook

function useTransition(
  options?: TransitionOptions
): [TransitionState, (toEnter?: boolean) => void, () => void];

Options

Name Type Default Description
enter boolean true Enable or disable enter phase transitions
exit boolean true Enable or disable exit phase transitions
preEnter boolean Add a 'preEnter' state immediately before 'entering', which is necessary to change DOM elements from unmounted or display: none with CSS transition (not necessary for CSS animation).
preExit boolean Add a 'preExit' state immediately before 'exiting'
initialEntered boolean Beginning from 'entered' state
mountOnEnter boolean State will be 'unmounted' until hit enter phase for the first time. It allows you to create lazily mounted component.
unmountOnExit boolean State will become 'unmounted' after 'exiting' finishes. It allows you to transition component out of DOM.
timeout number |
{ enter?: number; exit?: number; }
Set timeout in ms for transitions; you can set a single value or different values for enter and exit transitions.
onStateChange (event: { current: TransitionState }) => void Event fired when state has changed.

Prefer to read state from the hook function return value directly unless you want to perform some side effects in response to state changes.

Note: create an event handler with useCallback if you need to keep toggle or endTransition function's identity stable across re-renders.

Return value

The useTransition Hook returns a tuple of values in the following order:

  1. state:
{
  status: 'preEnter' |
    'entering' |
    'entered' |
    'preExit' |
    'exiting' |
    'exited' |
    'unmounted';
  isMounted: boolean;
  isEnter: boolean;
  isResolved: boolean;
}
  1. toggle: (toEnter?: boolean) => void
  • If no parameter is supplied, this function will toggle state between enter and exit phases.
  • You can set a boolean parameter to explicitly switch into one of the two phases.
  1. endTransition: () => void
  • Call this function to stop transition which will turn state into 'entered' or 'exited'.
  • You will normally call this function in the onAnimationEnd or onTransitionEnd event.
  • You need to either call this function explicitly in your code or set a timeout value in Hook options.

useTransitionMap Hook

It's similar to the useTransition Hook except that it manages multiple states in a Map structure instead of a single state.

Options

It accepts all options as useTransition and the following ones:

Name Type Default Description
allowMultiple boolean Allow multiple items to be in the enter phase at the same time.

Return value

The Hook returns an object of shape:

interface TransitionMapResult<K> {
  stateMap: ReadonlyMap<K, TransitionState>;
  toggle: (key: K, toEnter?: boolean) => void;
  toggleAll: (toEnter?: boolean) => void;
  endTransition: (key: K) => void;
  setItem: (key: K, options?: TransitionItemOptions) => void;
  deleteItem: (key: K) => boolean;
}

setItem and deleteItem are used to add and remove items from the state map.

License

MIT Licensed.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].