How Pass Function as Props To Child in React and Typescript.
React is one of the most popular JavaScript Library and the most used one, because of the features that brings with it to help to make highly dynamic responsive web and reuse the component to save time, but working plain JavaScript with not types leads to bugs when you run your code, to solve this problem Typescript came to saves you time catching errors and providing fixes before you run the code.
Install React with Typescript
To work with React and Typescript you have to two options, first one is create new project with Typescript template or add Typescript to an existing React project.
For creating new React & Typescript project run this code npx create-react-app react-typescript —-template typescript
.
To add Typescript to an existing React project run this code
yarn add typescript @types/node @types/react @types/react-dom @types/jest
And then rename every file from js
to tsx
and restart your server.
This is how our main component looks like
Let’s create a function takes a string as argument and ChildComp.tsx
component
In the line 5 we created a function called displayArg
take argument as string and void
means nothing will return. If you notice on line 11, Typescript catch and error but why? In react it suppose to be okay but in typescript is not, well because ChildComp
did not know anything about that there’s a props coming from app component, to fix that we have to tell type script that there’s a props coming with special structure.
Now after we told ChildComp
the error dispear because typescript now knows about a function coming as props called displayArg
, now we can access to that function in props.
Next article we will see how to use it.