Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding custom prop to React-Native element?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I couldn’t find similar case, any help?

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading