Home > Software design >  TypeScript. Assign JSX element to variable
TypeScript. Assign JSX element to variable

Time:05-18

I have a very simple function that returns an input and its value. The problem is that I don't know how to assign the JSX element to a variable. When using usual React, everything is fine, but with TypeScript, i have an error. Here is the function itself:

export const useInput = () => {
    const [val, setInputValue] = React.useState("");

    const inputValueHandler = (e: React.FormEvent<HTMLInputElement>) => {
        const currentTarget = e.target as HTMLInputElement;
        setInputValue(currentTarget.value);
    };
      
     const input: JSX.Element = <input value={val} onChange={inputValueHandler}/>;
    
    return [val, input];
  }

error appears here

     const input: JSX.Element = <input value={val} onChange={inputValueHandler}/>;

an error

"input" refers to a value, but is used as a type here. Did you mean "typeof input"?ts(2749)

CodePudding user response:

The problem is that you're not telling TypeScript that that code uses JSX, so it thinks the <input ... is the beginning of a type assertion (the angle bracket kind, not the as kind). (Playground link to the error with the playground configured not to allow JSX.)

If you tell TypeScript that that code is JSX (for instance, by putting it in a .tsx file), it works just fine. (Playground example showing no error when the playground is set to support JSX.)

  • Related