UniversalRouter Data => React Component

Example of passing path, params, query and hash from route to component

by Vladimir Kutepov

HTML

<script src="https://unpkg.com/[email protected]/universal-router.min.js"></script>
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<div id="root"></div>

Babel + JSX

// window.location
const location = new URL('https://example.com/point/10/20?z=30#bzz');

// example component
class YourComponent extends React.Component {
  render() {
    return <ul>
      <li>path: {this.props.path}</li>
      <li>params: {JSON.stringify(this.props.params, null, 2)}</li>
      <li>params.x: {this.props.params.x}</li>
      <li>params.y: {this.props.params.y}</li>
      <li>query: {JSON.stringify(this.props.query, null, 2)}</li>
      <li>query.z: {this.props.query.z}</li>
      <li>hash: {this.props.hash}</li>
    </ul>
  }
}

// routes
const route = {
  path: '/point/:x/:y',
  action({ path, params, query, hash }) {
    return {
      title: 'Example Page',
      component: <YourComponent path={path} params={params} query={query} hash={hash} />
    };
  },
};

// https://github.com/kriasoft/universal-router
UniversalRouter.resolve(route, {
  path: location.pathname,
  query: parseQuery(location.search),
  hash: location.hash,
}).then(result => {
  document.title = result.title;
  ReactDOM.render(result.component, document.getElementById('root'));
})

// https://github.com/sindresorhus/query-string
function parseQuery(qstr) {
  const query = {};
  const a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
  for (let i = 0; i < a.length; i++) {
    const b = a[i].split('=');
    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
  }
  return query;
}