Last active
March 14, 2018 22:31
-
-
Save nahumzs/fb1148778cd916ed00c261a41edef322 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class Collapsible extends Component { | |
state = { | |
// this state will be use by the uncontrolled component | |
startCollapsed: this.props.startCollapsed || true, | |
} | |
// How to detect if it's controlled or not | |
isControlled() { | |
return typeof this.props.isCollapsed !== "undefined"; | |
} | |
onClick() { | |
// even if it is uncontrolled the consuming app | |
// might be interested to know about this change | |
if (typeof this.props.onClick === "function") { | |
this.props.onClick(); | |
} | |
if (!this.isControlled()) { | |
this.setState({ startCollapsed: !this.state.startCollapsed }); | |
} | |
} | |
renderContent() { | |
const {children} = this.props; | |
// Decide base on the props what to do. | |
// DO NOT try to sync the state, that might open the door for ππππ (BUGS) | |
if (this.isControlled()) { | |
return this.props.isCollapsed ? null : children; | |
} | |
return this.state.startCollapsed ? null : children; | |
} | |
render() { | |
const {label, children} = this.props; | |
return ( | |
<div className="collapsible"> | |
<div>{label}<button onClick={() => this.onClick()}>toggle</button></div> | |
<div>{this.renderContent()}</div> | |
</div> | |
) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uncontrolled | |
<Toggle label="Hybrid uncontrolled component π"> | |
π¦πβ‘οΈπΆπΏπ΄ | |
</Toggle> | |
// Controlled | |
<Toggle | |
onClick={() => this.setState({ isCollapsed: !this.state.isCollapsed})} | |
isCollapsed={this.state.isCollapsed} | |
label="Hybrid controlled component π" | |
> | |
ππππ― | |
</Toggle> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment