npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-router-guard-dirty-state

v0.0.6

Published

Guard unsaved / dirty componets (usually containing forms) by alets when leaving both by onbeforeunload and react-roter routes.

Downloads

265

Readme

react-router-guard-dirty-state

Guard unsaved / dirty componets (usually containing forms) by issuing alert when leaving the component both by closing window (onbeforeunload) and / or navigating away by using react-roter routes.

About

This is higher order component for React (DOM) to let end users know that view they are about to leave has dirty state.

Leaving means

  1. navigating away from a route via react-router 4.
  2. closing browser tab / window altogether

This helper was put together for augmenting 1st case as react-router <Promt> is fine and dandy, but does not cover closing browser window. However this HOC can be used also with generic components / containers, where no routing is used.

By dirty state it is usually (and also here) meant when some form data is changed and unsaved. But it can be any state that is not resolved by user before closing the window or navigating away from the route.

Install

npm install react-router-guard-dirty-state --save-dev

Usage

ES2015 (ES6)

import guardDirtyState from 'react-router-guard-dirty-state';

CommonJS

const guardDirtyState = require('react-router-guard-dirty-state').default;

Decorate

/**
 * @param {PropTypes.bool} receiveBoolProp default = true
 * @param {PropTypes.node} React.Component (or React.PureComponent)
 */
guardDirtyState(receiveBoolProp)(React.Component)

Props

void guardDirtySetActive(bool)

On all cases where state become dirty issue this.props.guardDirtySetActive(true). On all cases where state becomes pristine (form is saved or reverted) issue this.props.guardDirtySetActive(false).

When leaving page while dirty is active user will get promted.

bool guardDirtyIsActive

This prop reflects current dirty state. Basically it means that issuing this.props.guardDirtySetActive(isDirty) where isDirty differs from previous state the component will receive prop update for guardDirtyIsActive. Do whatever you want with this.props.guardDirtyIsActive. Of course prop will be pushed only on dirty state change, not on every guardDirtySetActive().

Example shows simple case where SomeComponent is is under <Router> tree (any level deep as react-router 4 works this way now) and we can use this prop to set wether <Prompt /> should run on route change.

Note that receiving guardDirtyIsActive prop can be turned off by passing false to HOC if you do not use it (you do not use routes, or use some form management package for React that already handles dirty in component-space), which saves React reconciliation cycles.

export default guardDirtyState(false)(SomeComponent);

Example

'use strict';

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Prompt} from 'react-router-dom';
import guardDirtyState from 'react-router-guard-dirty-state';

class SomeComponent extends Component {
  static propTypes = {
    guardDirtySetActive: PropTypes.func,
    guardDirtyIsActive: PropTypes.bool,
    children: PropTypes.node
  };
  static defaultProps = {
    guardDirtyIsActive: false
  };

  constructor (props) {
    super(props);

    this.state = {
      formValues: {
        name: '',
        surname: ''
      }
    };

    this.handleFormChange = this.handleFormChange.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.setFormDirty = this.setFormDirty.bind(this);
  }

  setFormDirty (isDirty = false) {
    if (typeof this.props.guardDirtySetActive === 'function') {
      this.props.guardDirtySetActive(isDirty);
    }
  }

  handleFormChange (ev) {
    this.setFormDirty(true);

    const target = ev.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState((prevState, props) => ({
      formValues: {
        ...prevState.formValues,
        [name]: value
      }
    }));
  }

  handleFormSubmit (ev) {
    const {formValues} = this.state;
    alert(`Data was submitted. Name: ${formValues.name}, surname: ${formValues.surname}`);
    ev.preventDefault();
    this.setFormDirty(false);
  }

  render () {
    const {formValues} = this.state;
    return (
      <div>
        <h1>{'Submit your name and surname form'}</h1>
        <hr/>
        <form
          onSubmit={this.handleFormSubmit}
        >
          <label>
          {'Name:'}
            <input
              type="text"
              name="name"
              value={formValues.name}
              onChange={this.handleFormChange}
            />
          </label>
          <label>
          {'Surname:'}
            <input
              type="text"
              name="surname"
              value={formValues.surname}
              onChange={this.handleFormChange}
            />
          </label>
          <input
            type="submit"
            value="Submit"
          />
        </form>
        <Prompt
          when={this.props.guardDirtyIsActive}
          message="Changes you made may not be saved / There is unsaved data. Are you sure you want to leave this page?"
        />
        {this.props.children}
      </div>
    );
  }
}

export default guardDirtyState()(SomeComponent);

Building

npm run build:dev
npm run build:prod

Testing

N/A

Todo

Copy possible static methods using hoist-non-react-statics