Skip to content

Instantly share code, notes, and snippets.

@developit
Created October 25, 2016 20:09
Show Gist options
  • Save developit/7a1027bb8a88adf9a61570f2a2193f65 to your computer and use it in GitHub Desktop.
Save developit/7a1027bb8a88adf9a61570f2a2193f65 to your computer and use it in GitHub Desktop.
preact-views
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