Skip to content

Lift a react components state into the url

License

Notifications You must be signed in to change notification settings

stnwk/with-url-state

 
 

Repository files navigation

with-url-state

Greenkeeper badge

Lifts state out of a react component and into the url

color-example

Installation

yarn add with-url-state or npm install with-url-state --save if using npm

Usage

Check out the demo and the example/ directory

Using javascript

import { createBrowserHistory } from 'history';
import React from 'react';
import { withUrlState } from 'with-url-state';

const history = createBrowserHistory();

export const UrlForm = (props: OwnProps & UrlStateProps<LiftedState>) => (
  <div className="UrlForm">
    <div className="current-state" style={{ backgroundColor: props.urlState.color}}>
      <div>{props.urlState.color}</div>
    </div>
    <div className="color-buttons">
      <button className="Red" onClick={() => props.setUrlState({ color: 'red' })}>
        Red
      </button>
      <button className="Green" onClick={() => props.setUrlState({ color: 'green' })}>
        Green
      </button>
      <button className="Blue" onClick={() => props.setUrlState({ color: 'blue' })}>
        Blue
      </button>
    </div>
  </div>
);

export default withUrlState<OwnProps, LiftedState>(history, () => ({ color: 'blue' }))(UrlForm);

Using typescript

import { createBrowserHistory } from 'history';
import * as React from 'react';
import { withUrlState, UrlStateProps } from 'with-url-state';

const history = createBrowserHistory();

type OwnProps = {};
type LiftedState = { color: string };

export const UrlForm = (props: OwnProps & UrlStateProps<LiftedState>) => (
  <div className="UrlForm">
    <div className="current-state" style={{ backgroundColor: props.urlState.color}}>
      <div>{props.urlState.color}</div>
    </div>
    <div className="color-buttons">
      <button className="Red" onClick={() => props.setUrlState({ color: 'red' })}>
        Red
      </button>
      <button className="Green" onClick={() => props.setUrlState({ color: 'green' })}>
        Green
      </button>
      <button className="Blue" onClick={() => props.setUrlState({ color: 'blue' })}>
        Blue
      </button>
    </div>
  </div>
);

export default withUrlState<OwnProps, LiftedState>(history, { color: 'blue' })(UrlForm);

Motivation

Being able to have a sharable link which captures the state of a page can be very useful functionality for users.

This commonly occurs when viewing search results, filtering or querying over a data set or even tracking the currently visible portion on a map.

The api provided is:

About

Lift a react components state into the url

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 78.3%
  • HTML 12.4%
  • JavaScript 5.3%
  • CSS 4.0%