javascriptreactjstypescriptreact-nativereact-native-component

How to do component inheritance in React Native like on native platform?


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?


Solution

  • 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.