JSX in TypeScript and React Components
Explore how to implement JSX in TypeScript React components by creating class-based components with proper render methods. Understand how to handle JSX syntax requirements, embed TypeScript logic within render functions, and follow good practices to avoid common errors in returning JSX elements.
We'll cover the following...
JSX
As mentioned earlier, React uses a specific syntax for embedding what looks like HTML directly into our JavaScript code. This syntax is known as JavaScript XML or simply JSX. TypeScript has supported the JSX syntax from very early releases, with one main caveat. If we need to use JSX syntax, then our TypeScript file should be named .tsx instead of the normal .ts. With this in mind, let’s modify the generated src/App.tsx file and replace the contents with the following:
import React from "react";
import "./App.css";
class App extends React.Component {
render() {
return <div>Hello JSX</div>;
}
}
export default App;Here, we have the simplest example of a React component named App and how it
uses JSX syntax. We have defined a class named App that extends the class React.Component on line 3. This class has a ...