Introduction
There are multiple ways to use React components with typescript. In this article, we will see some of the ways to create components with typescript.
Prequsits
Basics of ReactJs
Need to familiar with Typescript
Get Started
On Typescript, you have to declare types for everything for example if you want to create a variable you have to declare the type of the variable like this: const name: string = 'ashraf';
now you can't change the value 'ashraf'
into other types, basic TS concepts.
Although you don't have to add type on this type of variable, because TS is enough smart to understand the basic variable type.
Basic Component
In this component, we created a type object called GreetType which has two property name: string
& age: number
Now you have to pass the GreetType object on component props, now you are ready to use the props value.
Remember: When you use this component you must have to pass the name props value as a string
type GreetType = {
name: string;
age?: number; // ? mark says that, this property is an optional property
};
export const Greet = (props: GreetType) => {
return (
<div>
My name is {props.name} & I'm {props.age} years old.
</div>
);
};
Union Type Component
In this component, we fixed the value of the status
type, the status property either be "loading"
or "success"
or "error"
you can't use other values like "waiting"
this will show an error
type StatusType = {
status: "loading" | "success" | "error"; //Union Type
};
export const Status = (props: StatusType) => {
return <h2>Status : {props.status}</h2>;
};
Children Component
If you want to use the children
property, first you have declared the type of children, here we used the React.ReactNode
, React.ReactNode
allows us to pass other components under this component.
You can also use children: string
children: number
whatever your need you can use.
type CardType = {
children: React.ReactNode;
};
export const Card = (props: CardType) => {
return <div>{props.children}</div>;
};
Custom Button Component
If you want to create a custom button you have to use React.ComponentProps<"tagName">
it as a type, this will help you to make a custom element with all attributes.
type CustomButtontype = React.ComponentProps<"button">; //React.ComponentProps helps us to add HTML elements
export const CustomButton = ( { children, ...rest }: CustomButtontype ) => {
//...rest means all the rest of other attributes
return <button {...rest}>{children}</button>;
};
That's a warp!
If you found this useful follow me for more articles like this one & I also share quality content on: