Skip to content

Instantly share code, notes, and snippets.

@ceuk
Last active April 18, 2019 11:20
Show Gist options
  • Save ceuk/4c55d5dea7b021496dd881fa1e2696ce to your computer and use it in GitHub Desktop.
Save ceuk/4c55d5dea7b021496dd881fa1e2696ce to your computer and use it in GitHub Desktop.
Allows you to switch between children using the component name and adds a nice slide/fade transition
import React, { Children } from 'react';
import { Transition } from 'react-transition-group';
import PropTypes from 'prop-types';
const visibilityStyles = {
entering: { transform: 'translateX(0)', opacity: 1 },
entered: { transform: 'translateX(0)', opacity: 1 },
exiting: { transform: 'translateX(-5%)', opacity: 0 },
exited: { transform: 'translateX(-5%)', opacity: 0 },
};
const Switch = ({ activeView, children }) => Children.map(children, child => (
<Transition
key={child.type.name}
mountOnEnter
unmountOnExit
in={activeView === child.type.name}
timeout={200}
>
{state => (
<div style={{ ...visibilityStyles[state], transition: 'all .2s ease-in-out' }}>
{child}
</div>
)}
</Transition>
));
Switch.propTypes = {
activeView: PropTypes.string.isRequired,
};
export default Switch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment