Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@oieduardorabelo
Created March 17, 2019 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oieduardorabelo/33992a50a142fffe56f093e20ac0bd10 to your computer and use it in GitHub Desktop.
Save oieduardorabelo/33992a50a142fffe56f093e20ac0bd10 to your computer and use it in GitHub Desktop.
`react-transition-group/Transition` example
import React from "react";
import Transition from "react-transition-group/Transition";
const duration = 300;
const Accordion = ({ in: inProp, children }) => {
const childrenType = typeof children.type;
if (childrenType === "undefined" || childrenType === "symbol") {
throw new Error(
`"Accordion" children should be a single element. Instead it received ${JSON.stringify(
childrenType
)}`
);
}
const cloned = React.cloneElement(children, {
ref: React.createRef(),
style: { overflow: "auto" }
});
return (
<Transition
in={inProp}
timeout={duration}
onEntering={node => {
const { current } = cloned.ref;
const { marginTop, marginBottom } = window.getComputedStyle(current);
const h =
parseInt(marginTop) + parseInt(marginBottom) + current.scrollHeight;
node.style.height = `${h}px`;
}}
onExiting={node => {
node.style.height = 0;
}}
>
{state => (
<div
aria-hidden={state === "exited"}
hidden={state === "exited"}
style={{
height: 0,
overflow: "hidden",
transition: `height ${duration}ms ease-in`,
visibility: state === "exited" ? "visible" : undefined
}}
tabIndex={state === "exited" ? -1 : undefined}
>
{cloned}
</div>
)}
</Transition>
);
};
class App extends React.Component {
constructor(p) {
super(p);
this.onToggle = this.onToggle.bind(this);
this.onRef = this.onRef.bind(this);
this.state = { inProp: false };
}
onToggle() {
window.requestAnimationFrame(() => {
this.setState({
inProp: !this.state.inProp
});
});
}
onRef(name) {
return node => {
this.reffs[name] = node;
};
}
render() {
return (
<React.Fragment>
<Accordion in={this.state.inProp}>
<div>
<h1>Hello!</h1>
<button type="button" onClick={() => alert("Hello!")}>
Hello!
</button>
</div>
</Accordion>
<button type="button" onClick={this.onToggle}>
Hello
</button>
</React.Fragment>
);
}
}
export { App };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment