0

My background is an iOS developer and in swift I could do MyInput: UITextField (swift component alternative to React Native Input). This meant that MyInput automatically got all the properties and functions that UITextField has. Currently in react native I do this like this:

interface Props {
    title?: string;
    text: string;
    onChangeText?: (string) => void;
    keyboardType?: KeyboardTypeOptions;
    disabled?: boolean;
    onBlur?: () => void;
}

export default function MyInput ({
    title, text, onChangeText, keyboardType, disabled = false, onBlur= (()=> null)}: Props)
{

return(
    <Input
        label={title}
        onChangeText={(text) => onChangeText(text)}
        value={text}
        keyboardType={keyboardType}
        disabled={disabled}
        onBlur={() => onBlur()}
    />);

Basically I have to add anything I want from Input into Props and then redirect it into Input. Is there a way that I could just upgrade Input without doubling most of the code and to have all the Input properties by default available in MyInput?

So methods like onBlur would have to be rewritten.

Or if anyone at least could tell me what to google to find such solution?

schmru
  • 591
  • 3
  • 8
  • 29
  • If i get you correctly, are you saying you want to pass props to MyInput component and then instead of rewriting the same properties again to Input component just pass it as it is to it? – Tushar Jul 06 '20 at 13:18
  • @Tushar If possible yes, or more precise what I thought was that MyInput would automatically have props that Input has, either way would help a lot. – schmru Jul 06 '20 at 13:21

1 Answers1

1

If I got you correctly, this is what you are looking for

export default function MyInput (props: Props) // get all the props
{

const myProps = { // change the key value pairs according to props that Input accepts
    ...props,
    label: props.text,
    value: props.text
}

return(
    <Input
        {...myProps}
    />);

If not please let me know, and I'll change it accordingly.

schmru
  • 591
  • 3
  • 8
  • 29
Tushar
  • 665
  • 5
  • 11
  • Your answer is very helpful, the only thing I am missing right now is, if there is a way that MyInput could automatically have all the input attributes without redefining them in Props. – schmru Jul 06 '20 at 14:12
  • 1
    The interface **Props** is just acting as a type checker for the props passed in, so I guess there's nothing that you can do to reduce that part of the code. It's actually fine to do this as when without using typescript we check for type of props we receive, using **PropTypes** we do have to define them like this. – Tushar Jul 06 '20 at 14:26
  • Ok, thank you so much for this help, it reduced my code a lot. – schmru Jul 06 '20 at 14:30