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:

import  { FC } from "react";
type Props = {
  title: string;
};
const Header:FC<Props>=({title})=>{
    return(
      <>
          <div className='App-header'>
          <p>Welcome to React! <b>{title}</b></p>
        </div>
        </>
    );
}

export default Header;

3. Update the App.tsx File

Pass the `title` prop to the <Header> component like this:

import Header from './component/header/Header';
import Footer from './component/footer/footer';

function App() {
  return (
    <>
    <div className="App">
     <Header title="I am from App!"/>
      <div>
        <h1>Home Page</h1>
      </div>
    <Footer/>
    </div>
    </>
  );
}

export default App;

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