Search code examples
typescriptreact-nativereact-native-paper

Extending react-native-paper Button and Text components in TypeScript


I was trying to make a reusable component using react-native-paper

the problem comes when I try to use extends a type from the package

import React from 'react';

import {Button, Text} from 'react-native-paper';

export type ButtonProps = React.ComponentProps<typeof Button>;

type CustomButtonProps = ButtonProps & {
title: string;
};

export const ButtonPaper: React.FC<CustomButtonProps> = ({title, ...props}) => {
return (
<Button mode="contained" {...props}>
  welcome
</Button>
);
};

everything is fine so far but when I try to use the component on the screen, typescript gives me that error

enter image description here

any solution for that?


Solution

  • You can extend it as shown below

    Create a file ButtonPaper.tsx

    // Packages Imports
    import * as React from "react";
    import { Button } from "react-native-paper";
    
    // Type for CustomButton
    export type CustomButtonProps = {
      title: string;
    } & React.ComponentProps<typeof Button>;
    
    // function component for CustomButton
    const ButtonPaper: React.FC<CustomButtonProps> = ({ title, ...props }) => {
      return (
        <Button mode="contained" {...props}>
          {title}
        </Button>
      );
    };
    
    // Exports
    export default ButtonPaper;
    

    Also, the children prop in Button component of react-native-paper is mandatory. So, to avoid typescript warning, you can do

    export type CustomButtonProps = {
      title: string;
    } & Omit<React.ComponentProps<typeof Button>, "children">;
    

    Working Example