Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import { h, cloneElement, Component } from 'preact';
  2.  
  3. /**
  4. * <Views view="home">
  5. * <Home name="home" />
  6. * <Other name="other" />
  7. * </Views>
  8. */
  9. class Views extends Component {
  10. state = {
  11. view: this.props.view, // can pass default view in as a prop
  12. params: {}
  13. };
  14.  
  15. // route to a given view
  16. route = (view, params) => {
  17. params = params || {};
  18. this.setState({ view, params });
  19. };
  20.  
  21. componentWillReceiveProps({ view }) {
  22. if (view!==this.props.view) this.route(view);
  23. }
  24.  
  25. // child components can call: this.context.route('some-view');
  26. getChildContext() {
  27. return { route: this.route };
  28. }
  29.  
  30. render({ children }, { view, params }) {
  31. // just render the child whose `name` prop matches the current view:
  32. let child = children.filter( child => child.attributes.name===view )[0];
  33. return child ? cloneElement(child, params) : null;
  34. }
  35. }
  36.  
  37.  
  38.  
  39. /**
  40. * <Link to="home">Home</Link>
  41. * <Link to="foo" params={{ foo:'bar' }} />
  42. */
  43. const Link = ({ to, params, ...props }, context) => (
  44. <a onClick={ () => context.route(to, params) } {...props} />
  45. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement