├── .gitignore ├── .npmignore ├── .prettierrc ├── .editorconfig ├── .eslintrc ├── src ├── utils.js └── index.jsx ├── .babelrc ├── webpack.demo.config.js ├── webpack.config.js ├── LICENSE.md ├── index.d.ts ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | es 4 | *.log 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .babelrc 2 | .eslint* 3 | .editorconfig 4 | .npmignore 5 | webpack.* 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "es5" 4 | } 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["react", "prettier"], 3 | "extends": ["airbnb", "prettier", "prettier/react"], 4 | "parser": "babel-eslint", 5 | "env": { 6 | "browser": true 7 | }, 8 | "rules": { 9 | "prettier/prettier": "error", 10 | "react/jsx-props-no-spreading": 0 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/prefer-default-export */ 2 | 3 | export const assert = (condition, message = 'Assertion failed') => { 4 | if (!condition) { 5 | if (typeof Error !== 'undefined') { 6 | throw new Error(message); 7 | } 8 | 9 | throw message; // fallback if Error not supported 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": "> 0.25%, not dead" 7 | } 8 | ], 9 | "@babel/preset-react" 10 | ], 11 | "plugins": [ 12 | "@babel/plugin-proposal-export-default-from", 13 | "@babel/plugin-proposal-class-properties" 14 | ], 15 | "env": { 16 | "test": { 17 | "plugins": ["@babel/plugin-transform-runtime"] 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /webpack.demo.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | devtool: process.env !== 'PRODUCTION' ? '#cheap-module-source-map' : false, 5 | entry: { 6 | demo: ['@babel/polyfill', './demo/index.js'], 7 | }, 8 | resolve: { 9 | alias: { 10 | 'redux-autoloader': './src/index', 11 | }, 12 | }, 13 | output: { 14 | filename: '[name].js', 15 | publicPath: '/', 16 | path: path.resolve(__dirname, 'demo'), 17 | }, 18 | module: { 19 | rules: [ 20 | { 21 | enforce: 'pre', 22 | test: /\.js$/, 23 | loader: 'eslint-loader', 24 | exclude: /node_modules/, 25 | }, 26 | { 27 | test: /\.js$/, 28 | loader: 'babel-loader', 29 | exclude: /node_modules/, 30 | }, 31 | ], 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | devtool: 'source-map', 5 | entry: './src/index.jsx', 6 | output: { 7 | publicPath: 'lib/', 8 | path: path.resolve(__dirname, 'lib'), 9 | filename: 'react-router-query-params.js', 10 | sourceMapFilename: 'react-router-query-params.map', 11 | library: 'react-router-query-params', 12 | libraryTarget: 'commonjs2', 13 | }, 14 | externals: { 15 | react: 'react', 16 | 'react-router': 'react-router', 17 | 'react-router-dom': 'react-router-dom', 18 | 'query-string': 'query-string', 19 | 'react-display-name': 'react-display-name', 20 | }, 21 | module: { 22 | rules: [ 23 | { 24 | enforce: 'pre', 25 | test: /\.js$/, 26 | loader: 'eslint-loader', 27 | exclude: /node_modules/, 28 | }, 29 | { 30 | test: /\.js$/, 31 | loader: 'babel-loader', 32 | query: { 33 | plugins: ['@babel/transform-runtime'], 34 | }, 35 | exclude: /node_modules/, 36 | }, 37 | ], 38 | }, 39 | }; 40 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Wolt Enterprises 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | type Omit = Pick>; 4 | 5 | type Partial = { [P in keyof T]?: T[P] }; 6 | 7 | export type InjectedQueryParams = { 8 | queryParams: QueryT; 9 | setQueryParams: (queryParams: Partial) => void; 10 | }; 11 | 12 | type RequiredDefault = { 13 | default: T | ((val: T, props: P) => T); 14 | validate: (val: T, props: P) => boolean; 15 | }; 16 | 17 | type OptionalDefault = { 18 | default?: T | ((val: T | undefined, props: P) => T); 19 | validate: (val: T | undefined, props: P) => boolean; 20 | }; 21 | 22 | export default function withQueryParams({ 23 | keys, 24 | stripUnknownKeys, 25 | queryStringOptions, 26 | }: { 27 | keys: { 28 | [K in keyof QueryT]: undefined extends QueryT[K] 29 | ? OptionalDefault 30 | : RequiredDefault; 31 | }; 32 | stripUnknownKeys?: boolean; 33 | queryStringOptions?: { 34 | arrayFormat?: 'none' | 'bracket' | 'index'; 35 | }; 36 | }):

( 37 | Wrapped: React.ComponentType

> 38 | ) => React.FunctionComponent>>; 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-router-query-params", 3 | "version": "1.0.4", 4 | "description": "Set query parameters with a schema for react-router.", 5 | "main": "./lib/index.js", 6 | "module": "./es/index.js", 7 | "types": "./index.d.ts", 8 | "scripts": { 9 | "build": "npm run lint && npm run build:commonjs && npm run build:es", 10 | "build:commonjs": "rimraf ./lib && cross-env BABEL_ENV=commonjs babel ./src --out-dir ./lib", 11 | "build:es": "rimraf ./es && cross-env BABEL_ENV=es babel ./src --out-dir ./es", 12 | "lint": "eslint --ext .jsx --ext .js ./src", 13 | "test": "cross-env NODE_ENV=test karma start", 14 | "test:watch": "npm run test -- --singleRun=false", 15 | "demo": "webpack-dev-server --config webpack.demo.config.js --content-base demo/", 16 | "prepublishOnly": "npm run build", 17 | "start": "npm run demo" 18 | }, 19 | "author": "nygardk", 20 | "license": "MIT", 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/woltapp/react-router-query-params" 24 | }, 25 | "keywords": [ 26 | "react", 27 | "router", 28 | "query", 29 | "param", 30 | "queryparam", 31 | "hoc", 32 | "component" 33 | ], 34 | "peerDependencies": { 35 | "react": ">=15.0.0", 36 | "react-router": ">=4.0.0", 37 | "react-router-dom": ">=4.0.0" 38 | }, 39 | "devDependencies": { 40 | "@babel/cli": "7.8.3", 41 | "@babel/core": "7.8.3", 42 | "@babel/plugin-proposal-class-properties": "7.8.3", 43 | "@babel/plugin-proposal-export-default-from": "7.8.3", 44 | "@babel/plugin-transform-runtime": "7.8.3", 45 | "@babel/polyfill": "7.8.3", 46 | "@babel/preset-env": "7.8.3", 47 | "@babel/preset-react": "7.8.3", 48 | "babel-eslint": "10.0.3", 49 | "babel-loader": "8.0.6", 50 | "cross-env": "6.0.3", 51 | "eslint": "6.8.0", 52 | "eslint-config-airbnb": "18.0.1", 53 | "eslint-config-prettier": "6.9.0", 54 | "eslint-loader": "3.0.3", 55 | "eslint-plugin-import": "2.20.0", 56 | "eslint-plugin-jsx-a11y": "6.2.3", 57 | "eslint-plugin-prettier": "3.1.2", 58 | "eslint-plugin-react": "7.18.0", 59 | "prettier": "1.19.1", 60 | "react": "15.5.4", 61 | "react-dom": "15.5.4", 62 | "react-router": "^4.2.0", 63 | "react-router-dom": "^4.2.2", 64 | "rimraf": "3.0.0", 65 | "webpack": "4.41.5", 66 | "webpack-cli": "^3.3.10", 67 | "webpack-dev-server": "3.10.1" 68 | }, 69 | "dependencies": { 70 | "prop-types": "^15.5.10", 71 | "query-string": "^6.8.0", 72 | "react-display-name": "^0.2.0" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-router-query-params 2 | 3 | [![npm version](https://badge.fury.io/js/react-router-query-params.svg)](https://badge.fury.io/js/react-router-query-params) 4 | [![Download Count](http://img.shields.io/npm/dm/react-router-query-params.svg?style=flat-square)](https://npmjs.org/package/react-router-query-params) 5 | 6 | > Set query parameters with a schema for react-router. 7 | 8 | ## Install 9 | 10 | ``` 11 | npm install --save react-router-query-params 12 | ``` 13 | 14 | ## Peer dependencies 15 | 16 | * react 17 | * react-router v. ^4.0.0 or ^5.0.0 18 | * react-router-dom v. ^4.0.0 or ^5.0.0 19 | 20 | ## Example 21 | 22 | ```jsx 23 | import withQueryParams from 'react-router-query-params'; 24 | ... 25 | 26 | const ExampleComponent = ({ 27 | queryParams, 28 | setQueryParams, 29 | }) = ( 30 |

31 |
32 | queryParams: {JSON.stringify(queryParams)} 33 |
34 | 35 | 38 |
39 | ); 40 | 41 | const ConnectedComponent = withQueryParams({ 42 | stripUnknownKeys: false, 43 | keys: { 44 | example1: { 45 | default: 'example-1-default', 46 | validate: value => !!value && value.length > 3, 47 | }, 48 | example2: { 49 | default: (value, props) => props.defaultValue, 50 | validate: (value, props) => 51 | !!value && !props.disallowedValues.includes(value) 52 | } 53 | } 54 | })(ExampleComponent); 55 | ``` 56 | 57 | ## API 58 | 59 | ### Props 60 | 61 | * __`queryParams`__ (object): All current query parameters as key-value pairs in an object. 62 | 63 | * __`setQueryParams`__ (function): Set one or more query parameters. 64 | ```js 65 | this.props.setQueryParam({ key1: 'value1', key2: 'value2' }) 66 | ``` 67 | 68 | ### HoC 69 | 70 | The library exports `withQueryParams` higher order component as default. The HoC takes a configuration object as the first argument, and has the following options: 71 | 72 | * __`stripUnknownKeys`__ (boolean) 73 | - if `true`, removes keys from query parameters that are not configured with `keys` 74 | - default: false 75 | 76 | * __`keys`__ (object) 77 | - example: 78 | ```js 79 | keys: { 80 | example: { 81 | default: 'default-value', 82 | validate: () => true 83 | } 84 | } 85 | ``` 86 | 87 | #### Key configuration object 88 | 89 | Key object is used to create a configuration for the query parameters that are intended to be used. 90 | Every key is configured with the following properties: 91 | 92 | * __`default`__ (any): Define the default value for the query parameter. If query parameter valiation fails or it is undefined, the HoC automatically sets the query parameter to this value. Examples: 93 | - `default: 'example'`: sets 'example' as default value 94 | - `default: (value, props) => props.defaultParam'`: sets `defaultParam` from the component props as default value 95 | - `default: undefined`: do not set query parameter at all by default 96 | 97 | * __`validate`__ (function): Validate the query parameter and revert to default value if validation does not pass. Examples: 98 | - `validate: () => true`: allow any alue 99 | - `validate: value => !!value && value.length > 2`: allow any value with more than two characters 100 | - `validate: (value, props) => props.allowedValues.includes(values)`: validate value based on props 101 | 102 | ## License 103 | 104 | MIT 105 | -------------------------------------------------------------------------------- /src/index.jsx: -------------------------------------------------------------------------------- 1 | import React, { PureComponent } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { Redirect, withRouter } from 'react-router-dom'; 4 | import queryString from 'query-string'; 5 | import getDisplayName from 'react-display-name'; 6 | 7 | import { assert } from './utils'; 8 | 9 | export default function withQueryParams({ 10 | keys, 11 | stripUnknownKeys = false, 12 | queryStringOptions, 13 | } = {}) { 14 | if (keys && stripUnknownKeys) { 15 | assert( 16 | Object.keys(keys).length > 0, 17 | 'at least one query param key must be configured' 18 | ); 19 | } 20 | 21 | if (keys) { 22 | Object.keys(keys).forEach(key => { 23 | assert(keys[key].validate, `Missing validate function for key ${key}`); 24 | assert( 25 | typeof keys[key].validate === 'function', 26 | `'validate' for ${key} must be a function` 27 | ); 28 | }); 29 | } 30 | 31 | const QUERYPARAMS_OPTIONS = { 32 | arrayFormat: 'none', // one of: 'none', 'bracket', 'index', 33 | ...queryStringOptions, 34 | }; 35 | 36 | return Wrapped => { 37 | class WithQueryParams extends PureComponent { 38 | setQueryParams = obj => { 39 | const { location, history } = this.props; 40 | 41 | const to = history.createHref({ 42 | pathname: location.pathname, 43 | search: queryString.stringify( 44 | { 45 | ...queryString.parse(location.search, QUERYPARAMS_OPTIONS), 46 | ...obj, 47 | }, 48 | QUERYPARAMS_OPTIONS 49 | ), 50 | }); 51 | 52 | history.push(to); 53 | }; 54 | 55 | render() { 56 | const { location } = this.props; 57 | const queryParams = queryString.parse( 58 | location.search, 59 | QUERYPARAMS_OPTIONS 60 | ); 61 | 62 | const newQueryParams = keys 63 | ? Object.keys(keys).reduce((acc, paramName) => { 64 | const defaultConf = keys[paramName].default; 65 | const defaultValue = 66 | typeof defaultConf === 'function' 67 | ? defaultConf(queryParams[paramName], this.props) 68 | : defaultConf; 69 | 70 | return { 71 | ...acc, 72 | [paramName]: keys[paramName].validate( 73 | queryParams[paramName], 74 | this.props 75 | ) 76 | ? queryParams[paramName] 77 | : defaultValue, 78 | }; 79 | }, {}) 80 | : queryParams; 81 | 82 | const allParams = stripUnknownKeys 83 | ? newQueryParams 84 | : { 85 | ...queryParams, 86 | ...newQueryParams, 87 | }; 88 | 89 | const searchString = queryString.stringify( 90 | allParams, 91 | QUERYPARAMS_OPTIONS 92 | ); 93 | 94 | if (location.search.replace('?', '') !== searchString) { 95 | return ( 96 | 99 | ); 100 | } 101 | 102 | const wrappedProps = { 103 | location, 104 | setQueryParams: this.setQueryParams, 105 | queryParams: allParams, 106 | }; 107 | 108 | return ; 109 | } 110 | } 111 | 112 | WithQueryParams.displayName = `withQueryParams(${getDisplayName(Wrapped)})`; 113 | 114 | WithQueryParams.propTypes = { 115 | location: PropTypes.shape({ 116 | search: PropTypes.string, 117 | pathname: PropTypes.string, 118 | }).isRequired, 119 | history: PropTypes.shape({ 120 | push: PropTypes.func.isRequired, 121 | createHref: PropTypes.func.isRequired, 122 | }).isRequired, 123 | }; 124 | 125 | return withRouter(WithQueryParams); 126 | }; 127 | } 128 | --------------------------------------------------------------------------------