Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript. Assign JSX element to variable

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading