Skip to content

Instantly share code, notes, and snippets.

@liamgriffiths
Last active December 6, 2018 14:13
Show Gist options
  • Save liamgriffiths/63dea6d5490e60283dfa to your computer and use it in GitHub Desktop.
Save liamgriffiths/63dea6d5490e60283dfa to your computer and use it in GitHub Desktop.
Sloppy switch/case demo in React.js/JSX
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"));
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
}
}
@Ashfaq-khan002
Copy link

Your work is very good. We love to see your work and keep working like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment