Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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} />
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement