react-transition-state

Zero dependency React transition state machine

README

React-Transition-State


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.




State diagram


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



Install


  1. ```bash
  2. # with npm
  3. npm install react-transition-state

  4. # with Yarn
  5. yarn add react-transition-state
  6. ```



Usage


CSS example


  1. ```jsx
  2. import { useTransition } from 'react-transition-state';
  3. /* or import useTransition from 'react-transition-state'; */

  4. function Example() {
  5.   const [state, toggle] = useTransition({ timeout: 750, preEnter: true });
  6.   return (
  7.     <div>
  8.       <button onClick={() => toggle()}>toggle</button>
  9.       <div className={`example ${state.status}`}>React transition state</div>
  10.     </div>
  11.   );
  12. }

  13. export default Example;
  14. ```

  1. ```css
  2. .example {
  3.   transition: all 0.75s;
  4. }

  5. .example.preEnter,
  6. .example.exiting {
  7.   opacity: 0;
  8.   transform: scale(0.5);
  9. }

  10. .example.exited {
  11.   display: none;
  12. }
  13. ```




styled-components example


  1. ```jsx
  2. import styled from 'styled-components';
  3. import { useTransition } from 'react-transition-state';

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

  6.   ${({ status }) =>
  7.     (status === 'preEnter' || status === 'exiting') &&
  8.     `
  9.       opacity: 0;
  10.       transform: scale(0.9);
  11.     `}
  12. `;

  13. function StyledExample() {
  14.   const [{ status, isMounted }, toggle] = useTransition({
  15.     timeout: 500,
  16.     mountOnEnter: true,
  17.     unmountOnExit: true,
  18.     preEnter: true
  19.   });

  20.   return (
  21.     <div>
  22.       {!isMounted && <button onClick={() => toggle(true)}>Show Message</button>}
  23.       {isMounted && (
  24.         <Box status={status}>
  25.           <p>This message is being transitioned in and out of the DOM.</p>
  26.           <button onClick={() => toggle(false)}>Close</button>
  27.         </Box>
  28.       )}
  29.     </div>
  30.   );
  31. }

  32. export default StyledExample;
  33. ```




tailwindcss example





Perform appearing transition when page loads or a component mounts


You can toggle on transition with the useEffect hook.

  1. ```js
  2. useEffect(() => {
  3.   toggle(true);
  4. }, [toggle]);
  5. ```




Comparisons with _React Transition Group_


|This
------
Use_Yes_
Controlled_No_
DOM_Imperative_
Render_Resort
WorkingYour
Bundle[![NPM](https://img.shields.io/bundlephobia/minzip/react-transition-group)](https://bundlephobia.com/package/react-transition-group)
Dependency[![NPM](https://badgen.net/bundlephobia/dependency-count/react-transition-group)](https://www.npmjs.com/package/react-transition-group?activeTab=dependencies)

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


  1. ```typescript
  2. function useTransition(
  3.   options?: TransitionOptions
  4. ): [TransitionState, (toEnter?: boolean) => void, () => void];
  5. ```

Options


NameTypeDefaultDescription
------------
`enter`booleantrueEnable
`exit`booleantrueEnable
`preEnter`boolean|
`preExit`boolean|
`initialEntered`boolean|
`mountOnEnter`boolean|
`unmountOnExit`boolean|
`timeout`number|
`onStateChange`(event:|

Return value


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

1. state:

  1. ```js
  2. {
  3.   status: 'preEnter' |
  4.     'entering' |
  5.     'entered' |
  6.     'preExit' |
  7.     'exiting' |
  8.     'exited' |
  9.     'unmounted';
  10.   isMounted: boolean;
  11.   isEnter: boolean;
  12.   isResolved: boolean;
  13. }
  14. ```

2. 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.

3. 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:

NameTypeDefaultDescription
------------
`allowMultiple`boolean|

Return value


The Hook returns an object of shape:

  1. ```js
  2. interface TransitionMapResult<K> {
  3.   stateMap: ReadonlyMap<K, TransitionState>;
  4.   toggle: (key: K, toEnter?: boolean) => void;
  5.   toggleAll: (toEnter?: boolean) => void;
  6.   endTransition: (key: K) => void;
  7.   setItem: (key: K, options?: TransitionItemOptions) => void;
  8.   deleteItem: (key: K) => boolean;
  9. }
  10. ```

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

License


MIT Licensed.