UNPKG

react-url-query

Version:

A library for managing state through query parameters in the URL in React. Works well with or without Redux and React Router.

85 lines (73 loc) 2.12 kB
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import configureUrlQuery from '../configureUrlQuery'; /** * This class exists to read in the router from context (useful in react-router v4) * to get an equivalent history object so we can push and replace the URL. */ export default class RouterToUrlQuery extends Component { static propTyps = { routerContext: PropTypes.object }; static contextTypes = { router: PropTypes.object }; render() { const { router: routerOldContext } = this.context; const { routerContext: RouterContext } = this.props; if (typeof RouterContext === "undefined") { return ( <RouterToUrlQueryLogic router={routerOldContext} > {React.Children.only(this.props.children)} </RouterToUrlQueryLogic> ) } return ( <RouterContext.Consumer> {routerNewContext => ( <RouterToUrlQueryLogic router={routerNewContext} > {React.Children.only(this.props.children)} </RouterToUrlQueryLogic> )} </RouterContext.Consumer> ); } } class RouterToUrlQueryLogic extends Component { static propTypes = { children: PropTypes.node, router: PropTypes.object, }; componentWillMount() { const { router } = this.props; if (process.env.NODE_ENV === 'development' && !router) { // eslint-disable-next-line console.warn( 'RouterToUrlQuery: `router` object not found in context. Not configuring history for react-url-query.' ); return; } let history; if (router.history && router.history.push && router.history.replace) { history = router.history; } else if (router.push && router.replace) { history = router; } else if (router.transitionTo && router.replaceWith) { history = { push: router.transitionTo, replace: router.replaceWith, }; } configureUrlQuery({ history, }); } render() { const { children } = this.props; return React.Children.only(children); } }