1

I am using a component that I cannot change directly, but I would like to extend.

import { Button } from '@external-library'

// Currently how the button component is being used
<Button click={() => doSomething()} />

// I would like to add a tabIndex to the button
<Button click={() => doSomething()} tabIndex={0} />

I cannot add an attribute because the component is not expecting a tabIndex. I cannot directly modify the Button component.

How can I extend the <Button /> component so I can add attributes like tabIndex, etc?

I was hoping something like the following would work:

export default class ExtendedButton extends Button { }
// except I'm dealing with functional components

2 Answers 2

1

You can't edit custom component implementation without changing its internals.

// You can't add tabIndex to internal button without changing its implementation
const Button = () => <button>Click</button>;

In such cases, you implement a wrapper with desired props:

const Component = () => {
  return (
    <div tabIndex={0}>
      <Button />
    </div>
  );
};

If the component forwarding ref (also depends to which element it forwarded in the implementation), you can use its attributes:

// Assumption that Button component forwards ref
const Button = React.forwardRef((props,ref) => <button ref={ref}>Click</button>);

<Button ref={myRef}/>
// Usage
myRef.current.tabIndex = 0;
Sign up to request clarification or add additional context in comments.

Comments

1

You can access the inner DOM button element using React refs(read here)

most likely the external-lib you use provide a ref prop for the Button component which you use to pass your own create ref

 const buttonRef = useRef(null);

 <Button ref={buttonRef}/>

Then you can use buttonRef.current to add tabIndex when your data is ready to be populated in like

useEffect( () => { 
  if(buttonRef && buttonRef.current){
    buttonRef.current.tabIndex = 2;
 }
}, [props.someProperty] );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.