react typescript in javascript

To use TypeScript in a React project, you first need to install TypeScript and its corresponding types for React. You can do this using npm:

index.tsx
npm install --save typescript @types/react @types/react-dom
60 chars
2 lines

Then, you can rename your .js files to .tsx to indicate that they are TypeScript React components. You can also create a tsconfig.json file to configure TypeScript:

index.tsx
{
  "compilerOptions": {
    "jsx": "react",
    "module": "esnext",
    "target": "es2015",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "strict": true,
    "esModuleInterop": true
  }
}
206 chars
12 lines

In your tsconfig.json, you should configure the jsx option as "react" to enable JSX support, and the esModuleInterop option as true to enable CommonJS and ES6 modules interoperability.

You can then use TypeScript in your React components by specifying the prop types and state types using TypeScript syntax:

index.ts
import React, { useState } from 'react';

interface Props {
  name: string;
}

const Greeting: React.FC<Props> = ({ name }) => {
  const [greeting, setGreeting] = useState(`Hello, ${name}!`);

  return <h1>{greeting}</h1>;
};

export default Greeting;
252 chars
14 lines

In this example, we define a component called Greeting that takes in a name prop of type string, and uses state to display a greeting message. We use the React.FC interface to specify the props type.

With these steps, you should now be able to use TypeScript in your React project.

gistlibby LogSnag