1

I would like to add componentDidUpdate() implementation to an existing external component.

For example lets assume that I want component XYZ to log information to console when it was updated and call another method from XYZ.

I probably could technically extend XYZ and add componentDidUpdate()

    import {ZYZ} from 'external-lib'
    class UpdatableXYZ extends XYZ{

        componentDidUpdate() {
            console.log('UpdatableXYZ updated')
            super.iWantToCallThisMethod();
        }

        render() {
          super.render();
        }
    }

but we should avoid any inheritance different than Component (haven't tried if above works, since I do not want to use inheritance).

Other option would be using HOC and use XYZ as a WrappedComponent, but then I cannot call method from XYZ.

    const updatable = () => WrappedComponent => {
        return class LoadingHOC extends Component {
            componentDidUpdate() {
                console.log('updated');
               //cannot call super.iWantToCallThisMethod();
            }

            render() {
                    <WrappedComponent {...this.props} />
            }
        };
    };

How I can achieve it?

  • Please don't forget to mark an answer as "accepted". This will show users who have the same problem that this specific answer helped solving your problem. – Rallen Jun 12 at 14:01
1

There is no straightforward way to achieve this without changing the initial component source. This is why most component libraries expose all possible events and handlers in props.

I probably could technically extend XYZ and add componentDidUpdate()

You can try this and if implemented properly, there shouldn't be an issue, but you must be aware that this would only work if the external component is a class component, and also you maybe need to invoke super.componentDidUpdate if the source component has its own implementation of the same.

1

A solution that is possible and mostly preferred in regards to this is the usage of Refs.

Refs provide a way to access DOM nodes or React elements created in the render method.

class UpdatableXYZ extends Component {
    constructor(props) {
        super(props);

        // Create the reference.
        this.xyzRef = React.createRef();
    }

    componentDidUpdate() {
        console.log('UpdatableXYZ updated');
        // Access the method of the reference
        this.xyzRef.current.iWantToCallThisMethod();
    }

    render() {
        // Bind the reference to the component instance
        return <XYZ ref={this.xyzRef} />
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.