Last active
December 6, 2018 14:13
-
-
Save liamgriffiths/63dea6d5490e60283dfa to your computer and use it in GitHub Desktop.
Sloppy switch/case demo in React.js/JSX
This file contains 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
import React, { Component } from "react" | |
import ReactDOM from "react-dom" | |
import { Switch, Case } from "switch_case" | |
class App extends Component { | |
constructor() { | |
super() | |
this.state = { | |
value: false | |
} | |
} | |
toggle() { | |
this.setState({ value: !this.state.value }) | |
} | |
render() { | |
return ( | |
<div> | |
<h1>demo app</h1> | |
<Switch condition={this.state.value}> | |
<Case value={true}> | |
<button onClick={::this.toggle}>{"yes"}</button> | |
</Case> | |
<Case value={false}> | |
<button onClick={::this.toggle}>{"no"}</button> | |
</Case> | |
</Switch> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<App />, document.getElementById("app")); | |
This file contains 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
import React, { Component, PropTypes } from "react" | |
const isDefined = x => typeof x !== "undefined" | |
const isCase = x => x instanceof Case | |
const isCaseArray = x => (x instanceof Array) && x.filter(isCase).indexOf(false) === -1 | |
export class Case extends Component { | |
static propTypes = { | |
value: PropTypes.any, | |
values: PropTypes.any | |
} | |
render() { | |
const { children } = this.props; | |
return children; | |
} | |
} | |
export class Switch extends Component { | |
static propTypes = { | |
condition: PropTypes.any.isRequired | |
} | |
static select(condition, cases) { | |
for (let i = 0; i < cases.length; i++) { | |
const c = cases[i]; | |
const { value, values } = c.props; | |
if (isDefined(values) && values.indexOf(condition) > -1) { | |
return c | |
} else if (isDefined(value) && value === condition) { | |
return c | |
} | |
} | |
return null | |
} | |
static getCases(children) { | |
if (isCaseArray(children)) { | |
return children | |
} else if (isCase(children)) { | |
return [children] | |
} else { | |
const name = children.constructor.name | |
throw new TypeError(`Expected instance of Case but got ${name}`) | |
} | |
} | |
render() { | |
const { children, condition } = this.props; | |
const cases = Switch.getCases(children) | |
const result = Switch.select(condition, cases) | |
return result | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your work is very good. We love to see your work and keep working like this.