Home > Software engineering >  Adding custom prop to React-Native element?
Adding custom prop to React-Native element?

Time:08-09

I am trying to add custom prop to <Pressable/>. The solution I tried is:

type StyledButtonProps = {
    correct: boolean,
    clicked: boolean
  }

const button = () => <Pressable></Pressable>
const StyledButton = React.cloneElement(button, {correct, clicked}) //Here this error comes at "button": 
      Argument of type '() => JSX.Element' is not assignable to parameter of type
      'ReactElement<{ correct: [boolean, Dispatch<SetStateAction<boolean>>];
      clicked: [boolean, Dispatch<SetStateAction<boolean>>]; }, string | 
      JSXElementConstructor<...>>'

And I will use it like this:

render(
   <StyledButton onPress={...} correct={...} clicked={...} /> 
)

Here also comes warning: JSX element type 'StyledButton' doesnot have any construct or call signatures.

I couldn't find similar case, any help?

CodePudding user response:

In React, to customize and add logic to a component, we create a component that renders the original and adds the styling or logic. So just create a new component that gets every prop that Pressable gets, and the new props.

import { Pressable, PressableProps } from "react-native";

interface StyledButtonProps extends PressableProps {
    correct: boolean;
    clicked: boolean;
}

const StyledButton = ({ correct, clicked, ...other }: StyledButtonProps) => { // other - any other prop
    // ...
    return <Pressable {...other} />; // This way you pass all original Pressable props
}
  • Related