DEV Community

MokaDevLight
MokaDevLight

Posted on

2 2

ReactJS's components written in Typescript

Actually you can use ReactJS's components in Typescript as in facebook's example. Just replace 'jsx' file's extension to 'tsx':

//helloMessage.tsx:
var HelloMessage = React.createClass({
 render: function() {
 return <div>Hello {this.props.name}</div>;
 }
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);
Enter fullscreen mode Exit fullscreen mode

But in order to make full use of Typescript's main feature (static type checking) should be done couple things:

1) convert React.createClass example to ES6 Class:

//helloMessage.tsx:
class HelloMessage extends React.Component {
 render() {
 return <div>Hello {this.props.name}</div>;
 }
}
ReactDOM.render(<HelloMessage name="John" />, mountNode);
Enter fullscreen mode Exit fullscreen mode

2) next add Props and State interfaces:

interface IHelloMessageProps {
name:string;
}
interface IHelloMessageState { //empty in our case } class HelloMessage extends React.Component {
constructor(){
super();
}
render() {
return
<div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(, mountNode);
Enter fullscreen mode Exit fullscreen mode

Now Typescript will display an error if the programmer forgets to pass props. Or if they added props that are not defined in the interface.

References:
ReactJSNotesForProfessionals Book

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay