How Pass Function as Props To Child in React and Typescript.
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
tsx and restart your server.
This is how our main component looks like
Let’s create a function takes a string as argument and
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.