react-showof
React-showof is a small (less than 500b) and opiniated component to help with (un)mounting transitions.
Problem
Many times in my workflow i just need to show a litle animation when showing and hidding a component.
Css transitions are good for animations based on state change, but the problem is that you might not want to have your component mounted because it may be heavy and the user may not even do the action to show it ever, so its a waste of rendering and DOM nodes.
If you conditionaly mount and apply the transitions it wont work, because you need to have a previous state to transition from.
Solution
Mount your component with a idle
state that will represent your initial styles like:
Then change it right away to the enter
state:
Now, how do you manage this state change, and what to do for unmount?
The solution could to use CSSTransition
from react-transition-group to managed that state changes.
I find it to litle bit over complicated and to have too many states that ends up being hard to understand what to use when.
ShowOf
ShowOf takes care of mounting and unmounting your component and pass the current state of the animation.
when
: boolean, do we ant to show or not our componentduration
: number, how many time do we want to wait until our component unmounts after setting when to falsenoAppear
: if we initially mount withwhen=true
, do we want to animate the appearence of it?noKeepProps
: when we are unmounting we pass the extra props from last positive render torender
render
: Component or function to render...props
: the rest of the props passed toShowOf
will be passed to therender
component or function
render
component/function receives as props:
when
propstate
the currentState
onTransitionEnd
to assing to the inner dom component so we can unmount after the animation run...props
plus the rest of the props.
Note onTransitionEnd
is only passed when you don't specify duration
State
is composed by 3 states idle
, enter
, exit
:
idle
when the component is mounted, its the begin style where you want to animatefrom
when mounting.enter
just after renderingidle
state, it is changed to this state, where you set theto
styes and transitions you want to applyexit
is wherewhen
becames false and we start unmounting the component, where you set the to styles for the unmount transition animation
Extra props passed to ShowOf
will be passed down to the render
component.
By default when unmounting we keep passing down the last "positive" props, that means the last props before changing when
to false.
Example
/* component style */ /* common styles for idle and exit as we use the same transitions for enter and exit */ /* styles to apply on enter state */ /* styles to apply on exit state */
{ const show setShow = React; return <div> <button onClick= >Toggle show ? 'off' : 'on'</button> <ShowOf when=show duration=300 render= { return <div className=`test `>Hello state</div>; } /> </div> ;}
Todo
- Docs
- Examples
- Tests