
How to Pass Props to React Components in TypeScript
Hey everyone! This is my third blog post. In the previous blogs, we learned how to create a Hello World app and how to create a component in React.
In this post, we will learn how to pass values (props) to a function component and bind them using TypeScript.
I’m continuing from the second blog’s project called "BASIC-Component". If you haven’t checked it yet, please do so first.
1. What are Props in a React Component?
Props (short for properties) are used to pass data from one component to another in React. They allow you to customize components and make them reusable.
2. Update the header.tsx File
Create a type for the props to ensure type safety in TypeScript:
type Props = {
title: string;
};
Now update your `Header` component to use this type and bind the prop value in a <b> tag:
3. Update the App.tsx File
Pass the `title` prop to the <Header> component like this:
4. Run the Project
You’re all set! Run your project with the following command:
npm start
It’s that easy! In this example, we passed a string value to our component, but you can also pass numbers, arrays, objects, and more. We’ll explore more advanced use cases in upcoming blog posts. Stay tuned!
For GitHub Project Please check https://github.com/ravinder25886/basic-component