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-final-form-graceful-field

v1.0.9

Published

parse and format that work how you actually want them to for react-final-form

Downloads

75

Readme

react-final-form-graceful-field

CircleCI Coverage Status semantic-release Commitizen friendly npm version

parse and format that work how you actually want them to for react-final-form

Why you would want to use this

If you've wanted to take number typed in and store the value as an actual number instead of text, without destroying UX, this is for you. That's what I wrote this for, although it supports any use case where you want to stash the raw value in field metadata.

The official advice from Erik Rasmussen is to store the raw string that was typed in and parse it in the submit handler, but that sucks:

  • Reparsing nested numeric fields within complex forms is a hassle
  • If you have validators that compare two numeric fields, for example a min <= max constraint, you have to reparse the numbers there too.

react-final-form-graceful-field allows you to use parse and format but it displays the raw value instead of formatted while the field is active or parse threw an error. That's right, parse can throw an error, and doing so will trigger a validation error on the field as well.

This way you can successfully type in 5.23, whereas a naive parse={parseFloat} approach will kill the . before you can type anything after it.

Try it out!

Demo CodeSandbox: https://codesandbox.io/s/react-final-form-graceful-field-example-n1onw?file=/src/index.js

Important

Important: react-final-form-graceful-field requires you to use the setFieldData mutator on your form:

import setFieldData from 'final-form-set-field-data'
const mutators = { setFieldData }

const MyForm = () => (
  <Form mutators={mutators} onSubmit={console.log}>
    ...
  </Form>
)

Example

// @flow

import * as React from 'react'
import { render } from 'react-dom'
import { Form } from 'react-final-form'
import { GracefulField } from '../src'
import setFieldData from 'final-form-set-field-data'

const format = (value: ?number): string =>
  Number.isFinite(value) ? String(value) : ''

const parse = (value: ?string): ?number => {
  value = value ? value.trim() : null
  if (!value) return null
  const parsed = Number(value)
  if (!Number.isFinite(parsed)) throw new Error(`invalid number`)
  return parsed
}

const mutators = { setFieldData }

render(
  <Form onSubmit={console.log} mutators={mutators}>
    {({ values, form, ...rest }) => (
      <div>
        <GracefulField
          name="price"
          format={format}
          parse={parse}
          component="input"
          invalidValue={NaN}
        />
        <button type="button" onClick={() => form.change('price', 5)}>
          Set to 5
        </button>
        <pre>{JSON.stringify({ values, rest }, null, 2)}</pre>
      </div>
    )}
  </Form>,
  (document.getElementById('root'): any)
)

API

GracefulField

import { GracefulField } from 'react-final-form-graceful-field'

Has the same API as <Field> except:

  • parse may throw an error, which will trigger a validation error.
  • Accepts an invalidValue property, which will be used if parse throws an error.
  • No formatOnBlur property. It formats on blur by default if parse didn't throw an error and you provide format.

useGracefulField

import { useGracefulField } from 'react-final-form-graceful-field'

Has the same API as useField except:

  • parse may throw an error, which will trigger a validation error.
  • Accepts an invalidValue property, which will be used if parse throws an error.
  • No formatOnBlur property. It formats on blur by default if parse didn't throw an error and you provide format.