3

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?

Hamed
  • 317
  • 1
  • 8
  • i think you can remove ButtonProps from CustomButtonProps – Rahman Haroon Feb 28 '22 at 06:51
  • actually, the CustomButtonProps is needed because I need all the props of the button to pass it later to the component – Hamed Feb 28 '22 at 06:57
  • can you try that by making into an interface with extends. something like this `interface CustomButtonProps extends ButtonProps {}` – Rahman Haroon Feb 28 '22 at 07:23
  • offtopic: couldt someone explain these pattern? i see this first `time.const ButtonPaper: React.FC` – Gismo1337 Feb 28 '22 at 07:24
  • @RahmanHaroon interface can't extend type as you know ), even I would have a TS error inside the component but I can ignore it if it works fine on the screen ) – Hamed Feb 28 '22 at 07:38

1 Answers1

3

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

Kartikey
  • 4,516
  • 4
  • 15
  • 40
  • just wanna add that typescript auto-complete wouldn't work with type CustomButtonProps = { title: string; } & Omit; ,better to use type CustomButtonProps = { title: string; } & Omit, 'children'>; – Hamed Feb 28 '22 at 08:32