Extract Component props value to another component in Typescript

Extract Component props value to another component in Typescript

Introduction

Regularly, we create a lot of components for different uses. Imagine that you passed some values by prop drilling in a component & now you need to use the same values in another component, what you should do?

Prerequisites

  • Need to know the basics of React.js

  • Good understanding of Typescript

Get Started

On Typescript we have a method called Extract Component. This method allows us to reuse one component's props values to another component. Let me show you how!

I created a component called Greet.tsx, in this component I passed some data by prop drilling & added a props type.

type GreetType = {
  name: string;
  age: number;
};

export const Greet = (props: GreetType) => {
  return (
    <div>
      Welcome {props.name}
    </div>
  );
};

Now I create another component called ExtractComponent.tsx, in this component, I imported the Greet component and declared it as a props type with the help of React.ComponentProps<typeof file-name>. Now we can use the Greet component props values in this component

import { Greet } from "./Greet";

export const ExtractComponent = (props: React.ComponentProps<typeof Greet>) => {
  return <div> My Name is: {props.name} and Im {porps.age} years old</div>;
};

Remember if you changed the value on the Greet component, your values also changed in this ExtractComponent file.

Conclusion

This Extract Component method is valuable when you need to use the same data on different components, remember if you used this method your data or values are dependent on the main component where all the data are passed.

At last

If you found this useful follow me for more articles like this one & I also share quality content on: