Skip to content

Instantly share code, notes, and snippets.

@rafabarbosa
Created June 1, 2020 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafabarbosa/ef55dacbab785f96d6974b03310af46c to your computer and use it in GitHub Desktop.
Save rafabarbosa/ef55dacbab785f96d6974b03310af46c to your computer and use it in GitHub Desktop.
Adicionando formatação dinâmica CPF ou CNPJ no input de acordo com a quantidade de números informados
import React, { useCallback } from 'react';
const Input = ({ ...props }) => {
const formatarCampo = useCallback(event => {
let value = event.currentTarget.value;
if (value.length <= 11) {
value = value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g,"\$1.\$2.\$3\-\$4");
} else {
value = value.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g,"\$1.\$2.\$3\/\$4\-\$5");
}
event.currentTarget.value = value;
});
const removerFormatacao = useCallback(event => {
let value = event.currentTarget.value;
value = value.replace(/\D/g, "");
event.currentTarget.value = value;
});
return <div>
<input { ...props } onFocus={removerFormatacao} onBlur={formatarCampo} />
</div>;
}
export default Input;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment