Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js

Here is the 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 handleSubmit = 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;

All type-related errors have been resolved. However, I am encountering syntax errors specifically around the HTML code within the return block.

For reference, here is an excerpt from 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"
  ]
}

https://i.stack.imgur.com/Ng0cC.png

https://i.stack.imgur.com/N68A9.png

After conducting some research, it appears that tweaking the tsconfig.json file and setting the jsx property to "react" may help. However, when running `npm run dev`, I encounter the following message:

https://i.stack.imgur.com/NseQ9.png

If anyone has insights on why I'm experiencing syntax errors related to HTML code during this conversion process, any assistance would be greatly appreciated.

Thank you

Answer №1

Make sure to include jsx in your tsconfig.json file by adding the following line:

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

--- Update ---

You can also use

"jsx": "preserve"
as an alternative setting.

This is a snippet of my own tsconfig.json configuration:

{
  "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"]
}

Answer №2

When I encountered an issue, I realized that the file extension for react files was set to ".ts" instead of ".tsx" for react components.

According to the react documentation:

https://i.stack.imgur.com/HTBAF.png

I hope this tip helps someone save time when transitioning a project from JavaScript to TypeScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Angular and JS do not have the functionality to toggle the split button

I have a question that seems similar to others I've seen, but I haven't found a solution yet. Can someone please review my code? In the component, I have {{$ctrl.init}} and {{$ctrl.people}} assigned. I am sure this assignment is correct because ...

Incorporating telepat-io into a Java Struts enterprise solution

Our J2EE enterprise application, built on Java Struts, has a static front end. Our team's architect has opted to enhance the user authentication by incorporating Ajax and JavaScript functionalities using telepat-io. The project is currently managed w ...

Finding Nested Key Paths in TypeScript for Objects and Arrays

I am in search of a unique method to create a TypeScript type that can take an object type and retrieve all the nested key paths, including properties within arrays as well. I want to exclude any default array properties such as "push" or "pop." While I ha ...

In HTML, data can be easily accessed, however, JavaScript does not have the same

When trying to access the 'data' element in a JSON object, I have encountered an issue. The element is accessible when called from HTML, but not when called in JavaScript. HTML: <p>{{geoJson.data}}</p> JavaScript: let scope; let d ...

Issues with sending FormData through Ajax POST requests over a secure HTTPS connection

We are currently experiencing issues with uploading pictures to our server. The process works smoothly on http sites, but encounters errors on https sites. An error message is displayed: Failed to load resource: the server responded with a status of 500 ( ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

Instructions for implementing personalized horizontal and vertical scrolling within Angular 9

I am currently working on an angular application where users can upload files, and I display the contents of the file on the user interface. These files may be quite long, so I would need vertical scrolling to navigate through them easily. Additionally, fo ...

What are some ways to avoid sorting parameters in AngularJS when making a GET request using $resource?

My resource is: angular.module('myApp.services') .factory('MyResource', ['$resource', function ($resource) { return $resource('http://example.org', {}, {}); }]); How I send a GET request: MyResourc ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. Is there a way to consolidate all these requests into one? My goal is to have a maximum of 8 bundles. This is ...

Could you explain the distinction between npm install and sudo npm install?

I recently switched to using linux. To install typescript, I ran the following command: npm i typescript Although there were no errors during the installation process, when I checked the version by typing tsc --version, I encountered the error message -bas ...