Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'value' does not exist on type 'never'. when use useRef hook in mui

I am using material UI to build a login and registration page, using useRef to return a TextFiled ref instance, and xxxRef.current.value to get the input value.

I can smoothly run my project and can get the value correctly,but the console always reminded me that:

Property 'value' does not exist on type 'never'.

Here is my code snippets:

const accountRef = useRef();

<TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="account"
            label="Account"
            name="account"
            autoComplete="account"
            autoFocus
            defaultValue={account}
            inputRef={accountRef}
/>


const payload = {
      account: accountRef.current?.value ?? '',
      password: passwordRef.current?.value ?? '',
      nickname: nicknameRef.current?.value ?? '',
};
like image 324
Liam_1998 Avatar asked Apr 28 '20 07:04

Liam_1998


People also ask

How do you fix property does not exist on type never?

The error "Property does not exist on type 'never'" occurs when we try to access a property on a value of type never or when TypeScript gets confused when analyzing our code. To solve the error, use square brackets to access the property, e.g. employee['salary'] .

How do I store a value in useRef hook?

Storing element references with useRef To do this, create the ref, and then pass it into the element: const Component = () => { const ref = useRef(null); return <div ref={ref}> Hello world </div>; }; With this reference, you can do lots of useful things like: Grabbing an element's height and width.

Why does useRef return undefined?

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose . current property is initialized to the passed argument. We didn't pass an initial value to useRef so its current property is set to undefined .

What type does useRef return?

useRef returns a mutable ref object whose .current property is initialized to the passed argument ( initialValue ). The returned object will persist for the full lifetime of the component. Essentially, useRef is like a “box” that can hold a mutable value in its .current property.


1 Answers

useRef is generic if you use it with TypeScript, so you can define the referenced element type like const ref = useRef<Type>();

Looking into the type definitions for the inputRef property in MaterialUI it states:

/**
 * Pass a ref to the `input` element.
 */
inputRef?: React.Ref<any>;

So for a fix you can define your refs like:

const accountRef = useRef<any>();

But the ref is passed through the input field inside the component, better type would be:

const accountRef = useRef<HTMLInputElement>();
like image 137
Martin Avatar answered Oct 05 '22 12:10

Martin