Conversion -- Class to Functional Components in React, and JSX to TSX
Developers can now use state and other React features without relying on class-based components thanks to release of React 16.8, and the inclusion of Hooks. This change makes it possible to write code that is shorter and more reusable. A thorough guide describing how to change a class-based component into a functional one is provided below:
Step 1: Remove the class keyword from component definition.
Step 2: Remove the render method.
Step 3: Change all methods into functions.
Step 4: Make sure to remove all references to it.
Step 5: For state management, use useState
hook.
Step 6: To manage side effects, use the useEffect
hook.
Now, let us examine a real-world illustration.
Following is a class-based component:
class SampleComponent extends React.Component {
state = {
name: "Shahrukh Khan"
};
setName = (name) => {
this.setState({ name });
};
render() {
return (
<div>
<h1>Hello, {this.state.name}</h1>
<input type="text" value={this.state.name} onChange={this.setName} />
</div>
);
}
}
We can convert this to a functional component by following below code example:
const SampleComponent = () => {
const [name, setName] = useState("Shahrukh Khan");
return (
<div>
<h1>Hello, {name}</h1>
<input type="text" value={name} onChange={setName} />
</div>
);
};
React 16.8 also introduced TypeScript which is a superset of JavaScript which is type strict and can detect errors during compile-time. This can help in writing reliable code.
For migrating JSX file to a TSX, follow the given step-by-step process:
- Change the file extension to .tsx.
- Make sure to import React and ReactDOM modules.
- To all JSX elements, add appropriate types.
- To type cast JSX elements to the appropriate types, use the
as
keyword.
Let’s present this with the help of example:
Following is the JSX file:
import React from 'react';function App() {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
}
It can be translated to the following TSX file:
import React, { Component } from "react";
import ReactDOM from "react-dom";
const App: Component = () => {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
Conclusion
Switching from class-based React components to functional ones and from JSX to TSX may require some effort. For more streamlined, reusable, and dependable code it can be a worthwhile endeavor.