Created
October 25, 2016 20:09
-
-
Save developit/7a1027bb8a88adf9a61570f2a2193f65 to your computer and use it in GitHub Desktop.
preact-views
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
import { h, cloneElement, Component } from 'preact'; | |
/** | |
* <Views view="home"> | |
* <Home name="home" /> | |
* <Other name="other" /> | |
* </Views> | |
*/ | |
class Views extends Component { | |
state = { | |
view: this.props.view, // can pass default view in as a prop | |
params: {} | |
}; | |
// route to a given view | |
route = (view, params) => { | |
params = params || {}; | |
this.setState({ view, params }); | |
}; | |
componentWillReceiveProps({ view }) { | |
if (view!==this.props.view) this.route(view); | |
} | |
// child components can call: this.context.route('some-view'); | |
getChildContext() { | |
return { route: this.route }; | |
} | |
render({ children }, { view, params }) { | |
// just render the child whose `name` prop matches the current view: | |
let child = children.filter( child => child.attributes.name===view )[0]; | |
return child ? cloneElement(child, params) : null; | |
} | |
} | |
/** | |
* <Link to="home">Home</Link> | |
* <Link to="foo" params={{ foo:'bar' }} /> | |
*/ | |
const Link = ({ to, params, ...props }, context) => ( | |
<a onClick={ () => context.route(to, params) } {...props} /> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment