Extending HTML elements in React and TypeScript while maintaining props

I just can’t wrap my head around this, I think I’ve probably tried half a dozen times and always resort to any... Is there a legal way to start with an HTML element, wrap it in a component and carry that in another component, so HTML Does the props go through everything? Essentially customize an HTML element? For example, something like:

interface MyButtonProps extends React.HTMLProps<HTMLButtonElement> {}
class MyButton extends React.Component<MyButtonProps, {}> {
    render() {
        return <button/>;
    }
} 

interface MyAwesomeButtonProps extends MyButtonProps {}
class MyAwesomeButton extends React.Component<MyAwesomeButtonProps, {}> {
    render() {
        return <MyButton/>;
    }
}

Using:

<MyAwesomeButton onClick={...}/>

Whenever I try to create such a composition, I get an error similar to:

The ref property for foo is not assigned to the target property.

+4
source share
1 answer

You can change the definition of your component to allow html button details

class MyButton extends React.Component<MyButtonProps & React.HTMLProps<HTMLButtonElement>, {}> {
    render() {
        return <button {...this.props}/>;
    }
}

typescript, 'MyButtonProps'

+5

Source: https://habr.com/ru/post/1661512/


All Articles