Creating React components in TypeScript

By default we’ll usually create a React component (in a .tsx file) using a React.Component base class, for example

export default class GridSampleComponent extends Component<{}, {}> {
   render() {
      return (
         <div></div>
      );
   }
}

But as per my post here we can also create components through functions, which ofcourse makes sense when you see a .jsx file which tend to default to using functions.

Hence we can create the following

const MyButton = (props: any) => {
   return 
      <Button variant="contained" 
         color="secondary">{props.children}</Button>;
};

In the code above we’ve basically created a new component from the function which takes properties which are implicitly passed to the function via React, i.e. the code for using the above might look like this

<MyButton>Hello</MyButton>

The child elements are passed through to our function. In this case it’s just the string “Hello”.