The simplest field formatting and masking tool for React.

Overview

Format As You Type

The simplest field formatting and masking tool for React.

Format fields the way you want using the input components you already use. Real-time. No hassle.

Overview

  • Install by running npm i format-as-you-type or yarn add format-as-you-type.
  • Import to a React component using import useFieldFormatter from 'format-as-you-type'.
  • Define a hook instance by passing in:
    1. A formatter (see below),
    2. A callback function that executes onChange (E.g., const birthdayFormatter = useFieldFormatter(formatDate, setBirthday);), and
    3. (Optionally) a custom ref prop to use on your field instead of the default ref={}.†
  • The hook instance contains props to pass to your input component. Implement them by simply adding { ...yourConstantName } at the end of the component's props.

Want to see more examples? Keep reading!

† As you will see further below, there are some custom input components that won't behave as expected when using ref={}.

Generic Formatters

While you can make your own formatters, there are a few that are ready to use:

  • formatDate
  • formatPhone
  • formatCreditCard
  • formatBigNumber
  • formatPostalCodeCanada

More generic formatters will be added with upcoming versions. However, if you have an idea for a new one, feel free to suggest it by creating an issue.

See the API header further below to learn more about each function's options and parameters.

Make Your Own Formatter

Generic formatters not getting the job done? Make your own! Just import formatString. Here's an example:

import { formatString } from 'format-as-you-type';

const formatCustom = (newInput, options, /* any additional parameters */) => {
  // Any extra logic goes here...

  return formatString(newInput, '0000 / 0000 \ 0000', options);
};

Custom formats can either contain placeholder characters such as A for letters and 0 for numbers (e.g. (000) 000-0000), or actual letters and numbers (e.g. (604) 123-4567). All that matters is where separators (non-numbers and non-letters) are placed.

***** The only rule is that the first parameter must be the string being formatted and the second parameter must accept an options argument. *****

Implementing a Formatter in a Plain HTML Field

Implementing useFieldFormatter in a plan HTML field is easy:

Birthday /* ... */ ); };">
import React from 'react';
import useFieldFormatter, { formatDate } from 'format-as-you-type';

const YourFormComponent = (props) => {
  const [birthday, setBirthday] = React.useState('');

  const birthdayFormatter = useFieldFormatter(formatDate, setBirthday);

  return (
    
   
/* ... */ /* ... */
); };

Implementing a Formatter in a Custom Component

When using useFieldFormatter on a custom text field component, you may encounter warnings, errors, or other unpredictable behaviour. That's because, in the context of our example, spreading birthdayFormatter in a component yields the following by default:


   
     ourChangeHandler(event)}
  ref={ourInternalInputRef}
/>

   

Some custom input components don't work without using a different prop instead, such as innerRef, inputRef, etc., or wrapping the component in a React.forwardRef.

Since we can't (yet) predict what type of component the hook will be spread into, the simplest solution, at the moment, is to provide the ref prop as the third argument when initializing useFieldFormatter.

In Material-UI's case, this is inputRef. If you use another library and run into problems, give their documentation a read. For our example, though, we'll stick to Material-UI:

/* ... */ ); };">
import React from 'react';
import useFieldFormatter, { formatDate } from 'format-as-you-type';
import TextField from '@mui/material/TextField';

const YourFormComponent = (props) => {
  const [birthday, setBirthday] = React.useState('');

  const birthdayFormatter = useFieldFormatter(formatDate, setBirthday, 'inputRef');

  return (
    
  
/* ... */ /* ... */ ); };

API

useFieldFormatter

useFieldFormatter(formatter, onChange, refProp = 'ref')

Parameters
Parameter Description
formatter A generic or custom formatter function (see below) that takes in (1) a string and (2) an options object, in that order.
onChange A callback function to update your field's value after if has been formatted. (This should have the structure (newValue) => setValueSomewhere(newValue))
refProp The prop to use to pass our internal prop to your input component. Is 'ref' by default for plain HTML fields, but can be replaced with inputRef, innerRef, or whichever prop is instructed by your specific component/library.

formatDate

formatDate(newInput, options, format = 'YYYY-MM-DD')

formatPhone

formatPhone(newInput, options, format = '(000) 000-0000')

formatCreditCard

formatCreditCard(newInput, options, infoType = 'NUMBER')

Special parameters
Parameter Description Options
infoType Whether to parse a credit card's number or its expiry date NUMBER, EXPIRY_2 (MM / YY), EXPIRY_4 (MM / YYYY)
Info
  • This formatter is intended for credit cards with 16-digit numbers.
  • If the first digit of a credit card's number is 3, it will be formatted like an AMEX card. Otherwise, it'll be formatted in groups of four digits.
  • If your form might take credit cards with more than 16 numbers, feel free to make a custom formatter using formatString (see further below).

formatBigNumber

formatBigNumber(newInput, options, locale)

Special parameters
Parameter Description Options
locale The region that determines how a number is formatted (e.g. 0,000,000 in English vs. 0.000.000 in French) en-US, fr-CA, etc...

† This list will be converted to type LocaleTypes = ... once this package is converted to TypeScript very soon.

formatPostalCodeCanada

formatBigNumber(newInput, options)

Info

This function simply formats strings to match the A0A 0A0 format.

formatString

formatString(newInput, format, options)

Special parameters
Parameter Description Default Value
options Customization for the formatter. See documentation below. {}
Options
Option Description Type (Default Value)
lettersAsSeparators Treat letters as a separator. I.e. don't format them. boolean (false)
numbersOnly Doesn't allow letters in input. boolean (false)
lettersOnly Doesn't allow numbers in input. boolean (false)
customFormatter Skip formatString() and use a custom formatter, such as JavaScript's built-in number.toLocaleString(), which is used in formatBigNumber(). function that returns a string
You might also like...

React tooltip is a React.JS Component that brings usefull UX and UI information in selected elements of your website.

React Tooltip ✅ React tooltip is a React.JS Component that brings usefull UX and UI information in elements of your website. Installation ⌨️ React Too

Dec 22, 2021

Airbnb-React - In this project, An Airbnb experience page clone is created to learn and implement React props concepts.

Airbnb-React - In this project, An Airbnb experience page clone is created to learn and implement React props concepts.

Create React Airbnb App In this project An airbnb experience page clone is created to learn and implement React props concepts. Objectives Learn about

Jun 28, 2022

React-app - Building volume rendering web app with VTK.js,react & HTML Using datasets provided in vtk examples (head for surface rendering and chest for ray casting)

SBE306 Assignment 4 (VTK) data : Directory containing Head and Ankle datasets Description A 3D medical viewer built with vtk-js Team Team Name : team-

Jul 19, 2022

a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense r

Dec 3, 2022

Simple React Social Network, built with React,Node,Express,MongoDB and Tailwind

Simple React Social Network, built with React,Node,Express,MongoDB and Tailwind

Full stack react social network application A mini social network application built with React,Typescript, Redux, Node, Express, MongoDB, and Tailwind

Dec 19, 2022

Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose.

spa-store Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose. Contributing Feedback Roadmap Releases Check

Jul 4, 2022

A personal project, made with React, React Native, Typescript and some of the most used front-end libraries.

A personal project, made with React, React Native, Typescript and some of the most used front-end libraries.

A personal project, made with React, React Native, Typescript and some of the most used front-end libraries.

Jul 23, 2022

React components and hooks for creating VR/AR applications with @react-three/fiber

React components and hooks for creating VR/AR applications with @react-three/fiber

@react-three/xr React components and hooks for creating VR/AR applications with @react-three/fiber npm install @react-three/xr These demos are real,

Jan 4, 2023

Basic React Project with React Router, ContextAPI and Login

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Jan 3, 2023
Owner
Mark Kopani
Full-Stack Developer & Data Scientist with a BSc. in Statistics (University of British Columbia)
Mark Kopani
Phonemask - Library for processing the phone input field in the web form. Only native javascript is used

phonemask Library for processing the phone input field in the web form. Only native javascript is used Usage: Adding a library to HTML <script type="a

Neovav 2 Sep 20, 2022
Prettier formatting for ?_trace=1 traces

datasette-pretty-traces Prettier formatting for ?_trace=1 traces Installation Install this plugin in the same environment as Datasette. $ datasette in

Simon Willison 4 May 26, 2022
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.

Recoil · Recoil is an experimental set of utilities for state management with React. Please see the website: https://recoiljs.org Installation The Rec

Facebook Experimental 18.2k Jan 8, 2023
Grid-tool - Small tool that allows you to integrate a predefined or generated grid into your front-end development environment.

Grid tool Small tool that allows you to integrate a predefined or generated grid into your front-end development environment. Tool installation includ

hmongouachon 2 Jan 4, 2022
An interactive CLI automation tool 🛠️ for creating react.js and next.js projects most fast and efficiently. ⚛️

An interactive CLI automation tool ??️ for creating react.js and next.js projects most fast and efficiently. ⚛️ About ℹ️ ReexJs CLI is an interactive

Alexis Guzman 27 Apr 12, 2022
A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router.

A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router. It also includes a theme switcher from light to dark mode.

Franklin Okolie 4 Jun 5, 2022
This is made for those who are learning react and are tired of doing create-react-app and having to delete those unused files

Easy React Pack (ERP) This is made for those who are learning react and are tired of doing create-react-app and having to delete those unused files. H

null 3 Jan 12, 2022
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and s

Victor Dantas 9 Jun 30, 2022
Soft UI Dashboard React - Free Dashboard using React and Material UI

Soft UI Dashboard React Start your Development with an Innovative Admin Template for Material-UI and React. If you like the look & feel of the hottest

Creative Tim 182 Dec 28, 2022
Finished code and notes from EFA bonus class on building a React project without create-react-app

React From Scratch Completed Code This is the completed code for the EFA bonus class on building a React project from scratch. Included are also markd

Conor Broaders 3 Oct 11, 2021