Setting children props in React functional component - typescript
A short tutorial on how to set children props in Rect for functional components in typescript
While setting children props in javascript comes without any problems, typescript on the other hand poses a slight problem due to the in built type checking which it comes with.
This typechecking has been a problem to some — as they prefer the “TYPE-LESS” javascript syntax — , and to many others (like myself) this brings a lot of advantages one of which is the code suggestion in your code editor of choice.
Anyways, this article doesn’t focus on the differences in typescript and javascript so I better get to it
The flexibilty of javascript (in types) allows javascript to set children props easily as is shown below
function Button (props) {
return <button>{props.children}</button>
}
This property can easily be utilized in javascript using the code
<Button>{/* add the child widget here */}
<some child component/></Button>
And there you have it.
You have correctly set the children props for a custom component in React javascript but with typescript doing the same raises errors.
To set the children props for a component in typescript you would have to take into account the type of the children and in this case, it is of type JSX.Element. The code is as follows:
const Button= ({children}: {children: JSX.Element}) => (
<div>
children
</div>
);
You access this component like any other component with a child as follows:
<Button>
{/* add the child component here*/}
<some child component/>
</Button>
There you have it. You have completely setup children props in react functional component, and even more you did it in typescript
Good luck and happy coding