DEV Community

Muhammad Haseeb
Muhammad Haseeb

Posted on

How to reuse component's props in TypeScript

Image description

We often find ourself defining types for the props that are not actually part of that component and are used in some other component.

Lets take a simple example:
Suppose we have a Parent and a Child component with following props.



import React from 'react';
import { Child } from './Child';

type Props = {
  greeting: string;
  firstName: string;
  lastName: string;
};

export const Parent: React.FC<Props> = ({ greeting, firstName, lastName }) => {
  return (
    <>
      <span> {greeting}</span>
      <Child firstName={firstName} lastName={lastName} />
    </>
  );
};


Enter fullscreen mode Exit fullscreen mode


import React from 'react';

type Props = {
  firstName: string;
  lastName: string;
};

export const Child: React.FC<Props> = ({ firstName, lastName }) => {
  return (
    <>
      <div>{firstName}</div>
      <div>{lastName}</div>
    </>
  );
};



Enter fullscreen mode Exit fullscreen mode

⚠️ Problem Statement:

Repetitive Props

  • Type for firstName and lastName are also defined in Parent because it needs to be passed down to the Child component.

Code Sync issues

  • If one part changes we need to make sure the others stays in sync.

  • If the Child component is used in a similar pattern elsewhere we need to make sure we update the props there too.

💡 Solution:

We can use ComponentProps to extract the Props directly form the component's type and use rest and spread syntax to avoid repetition.



import React, { ComponentProps } from 'react';
import { Child } from './Child';

type Props = ComponentProps<typeof Child> & {
  greeting: string;
};

export const Parent: React.FC<Props> = ({ greeting, ...childProps }) => {
  return (
    <>
      <span> {greeting}</span>
      <Child {...childProps} />
    </>
  );
};


Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Creating the parent's props by merging them with it's child's solves the code sync issues.
  • Makes a unique source of truth.

PS: If you only need some of the props in the Child component, you can use Partials.

#coding #softwareengineering #productivity #webdeveloper #cleancode #codingtips #javascript #webdev #devlife #programming #computerscience

Top comments (0)