React Tip: How to Reuse Children Prop in React and TypeScript

React Tip: How to Reuse Children Prop in React and TypeScript

ยท

2 min read

Hey fellow developers! ๐Ÿค“

Today, I'm going to talk about one of the common mistakes React and TypeScript beginners make while working with the children prop. So, you've built a reusable button component and want to pass some content to it. You might have written something like this:

import { ReactNode } from 'react';

type BaseButtonProps = {
  disabled?: boolean;
  color: 'primary' | 'success' | 'danger';
  children: ReactNode | ReactNode[] | JSX.Element | JSX.Element[];
};

const BaseButton = ({ children, disabled, color }: BaseButtonProps) => {
  return (
    <button
      className={color}
      disabled={disabled}
    >
      {children}
    </button>
  );
};

export default BaseButton;

This is a great start! You've defined the children prop and set its type as ReactNode, allowing you to pass in any React element or component as the children of the button.

However, what if you use the children prop in multiple components? This is where things get a little tricky.

If you copy and paste the same children prop definition into every component, you'll end up with a lot of duplicated code. This could be better and can make your codebase harder to maintain.

Here's where you can make use of a reusable type!

In a separate TypeScript file (let's call it common.props.ts), you can define a new type that you can use across multiple components:

export type WithChildren<T = Record<string, unknown>> = T & {
  children: ReactNode | ReactNode[] | JSX.Element | JSX.Element[];
};

Now, you can use this WithChildren type in your component like this:

import { WithChildren } from '../common/common.props';

type BaseButtonProps = WithChildren<{
  disabled?: boolean;
  color: 'primary' | 'success' | 'danger';
}>;

const BaseButton = ({ children, disabled, color }: BaseButtonProps) => {
  return (
    <button
      className={color}
      disabled={disabled}
    >
      {children}
    </button>
  );
};

export default BaseButton;

By defining the children prop in a separate, reusable type, you can use it in multiple components without duplicating the code. This helps keep your codebase clean and organized!

In conclusion, this is just one example of how to reuse props in React and TypeScript. Creating a reusable type like WithChildren can also reuse props like navigation, modal, etc. Doing so allows you to keep your code DRY (Don't Repeat Yourself) and makes it easier to maintain. Plus, it's a great way to keep things organized and consistent in your codebase. Give it a try and see how it improves your workflow. ๐Ÿ˜‰

Omar IZEM
Full Stack Developer | Building High-Quality Software & Sharing Knowledge

If you have any questions, feel free to contact me directly on my LinkedIn.

ย