0

I am using react-bootstrap Button in my application, and I want to declare the class ButtonPageChange class that extends Button to define the value 'btn-loading' in the property className.

Without using typescript I have the following React component:

export const ButtonPageChange = ({onClick, href, disabled, variant, size, className, children}) => {

    return (
        <Button onClick={onClick}
                href={href}
                disabled={disabled}
                variant={variant}
                size={size}
                className={'btn-loading ' + className ? className : ''}
                data-senna-off="true"
        >
            {children}
        </Button>
    )

};

How you can see i have to pass all the props to the Button component. I wanted to use Typescript to make this ButtonPageChange more clean. This is not a syntactically correct code but to give you an idea:

declare class ButtonPageChange extends Button {
    className: {'btn-loading ' + props.className},
    data-senna-off: "true"
}

I am starting with Typescript and I don't have any idea how to do this. Thanks

1 Answer 1

1

I follow your idea, however the problem here is shared between TS and JS, even if in TS you can use typed props to make this easier to follow along.

React is based on composition, so you can't really extend a component (inheritance). Even if you can do it, you can use a composition solution:

interface ButtonPageChange extends ButtonProps {}

function ButtonPageChange(props: ButtonPageChangeProps) { 
  const { className, ...buttonProps } = props; // Object destructuring to pass all props down to `Button`
  return (
    <Button 
      {...buttonProps}  // spread to pass properties to button
      className={'btn-loading ' + className ?? ''} // Null coaleshing operator
      data-senna-off="true"
    />
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.