question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React-IMask example does not work - forwardRef error

See original GitHub issue

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Current behavior 😯

The example documented here https://mui.com/components/text-fields/#integration-with-3rd-party-input-libraries with react-imask does not work, there is an error on line 25 “inputRef={ref}”:

Type ‘ForwardedRef<HTMLElement>’ is not assignable to type ‘ForwardedRef<HTMLElement> & (((el: MaskedElement) => void) | undefined)’. Type ‘null’ is not assignable to type ‘ForwardedRef<HTMLElement> & (((el: MaskedElement) => void) | undefined)’.ts(2322)

It looks like the ref is being passed incorrectly. I am using react-imask 6.2.2, react 17.0.2 and the latest MUI packages

Expected behavior 🤔

Component should work without error after being copy and pasted from the example doc

Steps to reproduce 🕹

Steps:

  1. Copy and paste code
  2. Run it
  3. Above error appears

Context 🔦

I am trying to integrate text mask into a MUI Text Field. I did this successfully in MUI v4 using react-text-mask but the new imask example does not seem to be working.

Your environment 🌎

`npx @mui/envinfo`
    System:
    OS: Windows 10 10.0.19042
    CPU: (8) x64 Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
    Memory: 2.83 GB / 15.81 GB
  Binaries:
    Node: 17.3.0 - C:\Program Files\nodejs\node.EXE
    npm: 8.3.2 - C:\Program Files\nodejs\npm.CMD
  Managers:
    pip3: 21.3.1 - C:\Python38\Scripts\pip3.EXE
  Utilities:
    Git: 2.27.0. - /mingw64/bin/git
  SDKs:
    Windows SDK:
      AllowAllTrustedApps: Disabled
      Versions: 10.0.17763.0
  IDEs:
    Android Studio: Version     2020.3.0.0 AI-203.7717.56.2031.7935034
    VSCode: 1.63.2 - C:\Users\danie\AppData\Local\Programs\Microsoft VS Code\bin\code.CMD
  Languages:
    Bash: 4.4.23 - C:\Program Files\Git\usr\bin\bash.EXE
    Perl: 5.30.2 - C:\Program Files\Git\usr\bin\perl.EXE
    Python: 3.8.2 - /c/Python38/python
  Databases:
    MongoDB: 4.2.6 - C:\Program Files\MongoDB\Server\4.2\bin\mongo.EXE
  Browsers:
    Chrome: 97.0.4692.99
    Edge: Spartan (44.19041.1266.0), Chromium (97.0.1072.62)
    Internet Explorer: 11.0.19041.1202
tsconfig
{
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "esnext",
    "target": "es5",
    "moduleResolution": "node",
    "jsx": "react",
    "allowJs": true,
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "typeRoots" : ["node_modules/@types", "src/types"]
  },
  "include": ["src"]
}

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
KiwiKiliancommented, Mar 30, 2022

Here is a CodeSandbox, see also.

I’m currently using the following workaround:

inputRef={ref as RefCallback<HTMLTextAreaElement | HTMLInputElement>}

Looks like a problem of the typing of inputRef when combined with forwardRef – therefore only the docs seem to provide a broken example. Parts of the MUI library are probably not involved in the problem and updating @mui/material did nothing for me.

0reactions
gcboaventuracommented, Nov 22, 2022

I’m trying to use Formik, MUI and IMask together.

But a loop happens when performing the onChange.

I couldn’t find the error in my code:

export const MaskInput: FC<Props> = ({
	className,
	isLoading,
	onChange,
	mask,
	...props
}): JSX.Element => {
	const [field, meta] = useField(props.name || 'name')

	const hasError = !!(meta.touched && meta.error)

	const handleMaskHelper = new HandleMaskHelper()

	const TextMaskCustom = React.forwardRef<HTMLElement, CustomProps>(function TextMaskCustom(
		props: any,
		ref: any
	) {
		const { onChange, ...other } = props
		return (
			<IMaskInput
				{...other}
				mask={handleMaskHelper.handle(mask)}
				inputRef={ref}
				onAccept={(value: any) => onChange({ target: { name: props.name, value } })}
				overwrite
			/>
		)
	})

	return (
		<>
			<TextField
				{...props}
				{...field}
				fullWidth
				error={hasError}
				className={className}
				size="small"
				InputProps={{
					inputComponent: TextMaskCustom as any
				}}
			/>

			{hasError && <ErrorMessage>{meta.error || 'Erro'}</ErrorMessage>}
		</>
	)
}
import { BaseTextFieldProps } from '@mui/material'

export interface Props extends BaseTextFieldProps {
	isLoading?: boolean
	onChange?: (event: string | number) => void
	mask: Mask
}

export type Mask = 'cpf' | 'cnpj' | 'mobile-phone' | 'fixed-phone' | 'cep'

export interface CustomProps {
	onChange: (event: { target: { name: string; value: string } }) => void
	name: string
}

export interface HandleMaskModel {
	handle(mask: Mask): string
}

Read more comments on GitHub >

github_iconTop Results From Across the Web

Receiving 'Function components cannot be given refs' error ...
First, the 'findDOMNode is deprecated in StrictMode...' error appears to be an issue with the react-input-mask library. The library is no ...
Read more >
react-imask - npm
Start using react-imask in your project by running `npm i react-imask`. ... access to nested input // DO NOT USE onChange TO HANDLE...
Read more >
warning: function components cannot be given refs. attempts to ...
Iget error 'Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?' . How...
Read more >
react-imask + styled-components + react-hook-form
CodeSandbox is an online editor tailored for web applications. ... react-imask + styled-components + react-hook-form.
Read more >
React Text Field component - Material UI - MUI
Customization does not stop at CSS. You can use composition to build custom components and give your app a unique feel. Below is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found