M
M
MaZaAa2019-02-21 21:32:02
typescript
MaZaAa, 2019-02-21 21:32:02

React + Typescript custom component problem, how to solve?

Versions:

"@types/react": "^16.8.4",
"@types/react-dom": "^16.8.2",
"typescript": "^3.3.3",

Input component code :
import * as React from 'react';
import CSSModules from 'react-css-modules';


interface ComponentProps {
    innerRef?: React.RefObject<HTMLInputElement>;
    onKeyPress?: (e: any) => void;
    onKeyDown?: (e: any) => void;
    onFocus?: (e: any) => void;
}


@CSSModules(require('./styles.scss'), { allowMultiple: true })
class Input extends React.Component<ComponentProps> {
    render() {
        let {innerRef, ...props } = this.props;

        return (
            <input {...props} styleName="input" ref={innerRef} />
        );
    }
}

export default React.forwardRef((props, ref?: React.RefObject<HTMLInputElement>) => <Input innerRef={ref} {...props}/>);

A piece of code where this component is used:
<Input 
    ref={this.inputRef}
    onKeyPress={(e) => { e.preventDefault(); }}
    onKeyDown={(e) => { e.preventDefault(); }}
    onFocus={this.onInputFocus.bind(this)}
    placeholder={placeholder}
/>

And I get this error:
Type '{ ref: RefObject<HTMLInputElement>; onKeyPress: (e: any) => void; onKeyDown: (e: any) => void; onFocus: any; placeholder: string; }' is not assignable to type 'IntrinsicAttributes & RefAttributes<HTMLInputElement>'.
  Property 'onKeyPress' does not exist on type 'IntrinsicAttributes & RefAttributes<HTMLInputElement>'

The problem is not only specifically in this component, but in any of this kind.
What am I doing wrong? What needs to be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2019-03-19
@aM-aM

Try like this

export default React.forwardRef<
  HTMLInputElement,
  ComponentProps
>((props, ref?: React.RefObject<HTMLInputElement>) => <Input innerRef={ref} {...props}/>);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question