skip to Main Content

I am in the process of converting my Javascript code to TypeScript for a web application I am making on top of Next.Js

The following is my converted code:

'use client'

import React, { useState, ChangeEvent, FormEvent } from 'react';

interface FormData {
  email: string;
}

interface MessageStatus {
  message?: string; 
  success?: boolean;
}

interface ErrorResponse {
  error: string;
}

const EmailSubmissionComponent: React.FC = () => {
  const [formData, setFormData] = useState<FormData>({email: ''});
  const [messageStatus, setMessageStatus] = useState<MessageStatus>({});

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  const handleSumbit = async (event: FormEvent<HTMLFormElement>) => {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; //Should remove if not testing locally. 
    event.preventDefault();

    if (formData.email != "") {
      try {
        const response = await fetch('REDACTED', { //Change for production
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formData)
        });
  
        console.log('Response:', response); // Log response
        if (response.ok) {
          const responseBody = await response.json();
          // console.log('Response Body:', responseBody);
          setMessageStatus({message: "", success: true})
          // console.log('Form submitted successfully');
        } else {
          const errorResponse: ErrorResponse = await response.json(); 
          setMessageStatus({message:errorResponse.error, success:false})
          console.error('Form submission failed');
        }
      } catch (error :any) {
        setMessageStatus({message: "Network Error: Please try again shortly", success: false})
        console.log("Printing Errors:", error.message);
  
      }
    }
  };

  return (
    <div className="flex flex-col sm:w-[600px]">
      <form onSubmit={handleSubmit} className="flex flex-col sm:flex-row">
        <input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="E-mail Address" className="sm:flex items-stretch flex-grow focus:outline-none block rounded-lg sm:rounded-none sm:rounded-l-lg pl-4 py-2"></input>
        
        <button type="submit" className="sm:mt-0 sm:w-auto sm:-ml-2 py-2 px-2 rounded-lg font-medium text-white focus:outline-none bg-logo-blue">
          Stay in the Loop
        </button>
        
      </form>
      {messageStatus.message && <div className="border-2 rounded border-red-700 bg-red-300 py-2 px-2 mt-1">
        {messageStatus.message}</div>}
      {messageStatus.success && <div className="border-2 rounded border-green-700 bg-green-300 py-2 px-2 mt-1">
        Congrats! You have signed up. Stay Tuned!</div>}
    </div>
  );

}

export default EmailSubmissionComponent;

I have addressed all type related error.
I am still getting syntax errors around the HTML code I have written in the return block.

For Reference the below is my tsconfig.json file

{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "noEmit": true,
    "incremental": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "plugins": [
      {
        "name": "next"
      }
    ]
  },
  "include": [
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

enter image description here

enter image description here

Through some research I have come across solutions that relate to the tsconfig.json file and setting the jsx property to be "react", but then running npm run dev I get the below message:

enter image description here

Any guidance on why I am getting a syntax error at my HTML code when doing this conversation would be much appreciated.

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    My issue was that I wrote the file extension for the react files to be .ts but it should be a .tsx extension for react components.

    From the react docs:

    enter image description here

    I hope this will save someone else alot of time when converting a project over form javascript to typescript.


  2. Enable jsx in tsconfig.json add this line:

    "compilerOptions": {
      "jsx": "react"
    }
    

    Edit

    "jsx": "preserve" should also work

    This is what my tsconfig.json looks like:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "plugins": [
          {
            "name": "next"
          }
        ]
      },
    
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
      "exclude": ["node_modules"]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search