Skip to content

Instantly share code, notes, and snippets.

@daniele-zurico
Created October 16, 2018 17:25
Show Gist options
  • Save daniele-zurico/be8914f93bc4f4c4a6f14031a95af82e to your computer and use it in GitHub Desktop.
Save daniele-zurico/be8914f93bc4f4c4a6f14031a95af82e to your computer and use it in GitHub Desktop.
import React, { Component, cloneElement, Children } from "react";
class ExpansionPanel extends Component {
state = {
show: false
};
toggleContent = () => {
this.setState(prevState => ({
show: !prevState.show
}));
};
render() {
const childrenWithNewProps = Children.map(
this.props.children,
(child, i) => {
// doesn't display the content if `show` is false
if (child.type.name === "expansionPanelContent" && !this.state.show) {
return null;
}
// map the toggle event on the title
if (child.type.name === "expansionPanelTitle") {
return cloneElement(child, {
onClick: this.toggleContent
});
}
return cloneElement(child);
}
);
return <div>{childrenWithNewProps}</div>;
}
}
export default ExpansionPanel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment