Created
June 1, 2020 02:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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