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

Exploring the world of JSON files using JavaScript

Basically, my bot responds to a command (!accounts) by providing users with information based on their ID. For example, if an ID of 662 sends the command !account, the bot will search for steamID 662 in the json files and display the currency and correspon ...

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

Formatting Time in Angular 2 Using Typescript

Upon reviewing my date source, I found the following: TimeR ="2017-02-17 19:50:11 UTC"; Within the HTML file, I implemented this code snippet <span class="text-lg">{{TimeR | date: 'hh:mm'}}</span> The current output displays the t ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Is it possible to return a promise within the .then function in AngularJS?

I have a unique service called "usersService". I want to create a special method that interacts with another custom service I built. This other service has two handy methods: getUser() and getCurrentUser(). The getCurrentUser() method relies on the injecte ...

CombineReducers takes all the reducer content and unpacks it into a single reducer

As I work on developing a small application, I am contemplating the best strategy for organizing reducers within it. My objective is to retrieve JSON data from the application state and structure it as shown below: { "fruits": [ {"appl ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

Node.js is receiving an empty body from Postman when using form-data in the request

Even though I've searched extensively, I still have not found a solution to my specific issue despite it being asked before. const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

Guide on converting a JSON containing nested JSONs into an HTML table

Currently, I am working with a JSON data structure that contains nested dictionaries. My goal is to create an HTML table where each top-level key serves as a column in the table. The inner key-value pairs should be represented as a single text within cells ...

Does anyone have an example of how to integrate Passport Google OAuth2 with Next.js?

If anyone has experience working with passport google oauth2 in a Next.js project, I would appreciate any examples of code you can share. While there are resources available for implementing this in Node.js, the specifics of routes, middleware, and callbac ...

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

Issues with the Rendering of Child Components in React

I have developed a main component that contains two child elements, where one of the children is attempting to send data back to the parent's state. I am not encountering any runtime errors when running the code, but the child component that is suppos ...

Publishing a NodeJS + Express + MySQL application on Heroku involves deploying the server side only, excluding the React frontend

I have a React + NodeJS + Express + MySQL project that we're trying to deploy on Heroku. It's set to auto deploy whenever something is pushed to the master branch of GitHub. The problem we're facing is that while the server routes are deplo ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

Guide to modifying the class color using javascript

I am experiencing an issue with this particular code. I have successfully used getElementById, but when I try to use document.getElementsByClassName("hearts");, it does not work as expected. This is a snippet of my HTML code: status = 1; function change ...

Encountering difficulty inserting ajax response into a specific div element

What could be the issue? I've included the getElementById and I am receiving a response, as confirmed by Firebug. The response is correct, but for some reason it's not populating my div area. <script> $(document).ready(function () { $( ...

Populating form inputs with FCKeditor content prior to form submission

Currently, I am working on resolving an issue with a form on a website that relies on javascript for field validation. It has come to my attention that certain fields utilize fckeditor, causing the form field values to remain unset until the submit button ...

What is the best way to incorporate multiple functions within a React button?

I need to implement a functionality where the startClick function is triggered on BackButton click before executing the dispatch (giveForm2PreviousStep(props.currentStep, props.goToStep)) method. How can this be achieved? Inquiry JS const Inquiry = props ...

Finding the actual path in any scenario using JavaScript ($.ajax)

Here is the structure of my project: Sil -> css -> js -> clients -> index.php -> response.php index.php I am facing an issue related to the folder 'clients'. My website URL can have different va ...

Why is the Express validator failing to work with the posted value?

I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why. router.po ...