I am having a form in React TypeScript which looks like this:
<form onSubmit={handleSubmit}>
<input type="text" className="form-control" ref={firstName} name="firstName" id="firstName"/>
<input type="text" className="form-control" ref={lastName} name="lastName" id="lastName"/>
</form>
const handleSubmit = e => {
e.preventDefault();
const data = {
firstName: firstName.current.value,
lastName: lastName.current.value,
}
let formdata = JSON.stringify(data);
history.push({
pathname: '/review',
state: { details: formdata }
});
}
const firstName = React.useRef(null);
const lastName = React.useRef(null);
This works fine as we are getting empty values in firstName and lastName of the field. But when I change it to:
const firstName = React.useRef(SomeObject.name);
And remove the value inside the handleSubmit method,
const handleSubmit = e => {
e.preventDefault();
const data = {
firstName: firstName.current, <-- Change here
lastName: lastName.current.value,
}
let formdata = JSON.stringify(data);
history.push({
pathname: '/review',
state: { details: formdata }
});
}
I am getting the following error:
TS2322: Type 'MutableRefObject<string>' is not assignable to type 'LegacyRef<HTMLInputElement>'.
Type 'MutableRefObject<string>' is not assignable to type 'RefObject<HTMLInputElement>'.
Types of property 'current' are incompatible.
Type 'string' is not assignable to type 'HTMLInputElement'.
At reference(ref={firstName})
What did I do wrong here? I have just initialized the state variable statically instead of null, it should work fine right? Could anyone help me point out where am I missing, I have tried multiple ways of using this reference but in vain.
Edit: CodeSandbox link: https://codesandbox.io/s/cool-cache-hzu6r?file=/src/App.js
When you assign a ref to the ref property of a component it will become a ref to that component when it mounts.
In your case it will become a ref to the HTMLInputElement. So typescript expects a ref with type React.LegacyRef to be assigned to the ref property of the input element.
React.useRef(null) returns a ref with the type React.MutableRefObject which can be assigned to React.LegacyRef, because any can be assigned to HTMLInputElement or anything else.
React.useRef(SomeObject.name) returns React.MutableRefObject (because SomeObject.name is a string) and can not be assigned to React.LegacyRef because string is not a HTMLInputElement.
What you doing wrong here depends on what you a trying to do.
If you want to have a reference to an element you assign a result of React.useRef() to the ref property of the component that renders the element.
If you want to pass a ref to a component as prop you do it with some different property eg. someRef.
If you want to have a state variable you use state and not refs.