Refactoring UNSAFE_componentWillReceiveProps

977 Views Asked by At

I have an IFrameComponent component, inspired by this post.

It looks basically like this :

class IFrameComponent extends React.Component {
    shouldComponentUpdate() {
        return false;
    }

    componentWillReceiveProps(nextProps) {
        if(this.props.content !== nextProps.content) {
            const html = getHTMLFromContent();
            const fdoc = this.iFrame.contentDocument;
            fdoc.write(html);
        }
    }

    render() {
        return (<iframe sandbox="..." ref={f => this.iFrame = f} />);
    }
}

Now that componentWillReceiveProps is considered unsafe, I'm trying to get rid of it.

The ways React advices to refactor componentWillReceiveProps are basically either to use static getDerivedStateFromProps or componentDidUpdate

Sadly, componentDidUpdate will never get called, because shouldComponentUpdate returns false (and I think this is fine ?) and I wouldn't be able to access this.iFrame reference in the static method getDerivedStateFromProps.

How would one refactor this code ?

1

There are 1 best solutions below

4
On

I think, One possible way is:

let iFrameRefs = {}

class IFrameComponent extends React.Component {
    static getDerivedStateFromProps (props) {
        if (iFrameRefs[props.id]) {
            const html = getHTMLFromContent();
            const fdoc = iFrameRefs[props.id].contentDocument;
            fdoc.write(html);
        }
        return null
    }

    shouldComponentUpdate() {
        return false;
    }

    render() {
        return (<iframe sandbox="..." ref={f => iFrameRefs[this.props.id] = f} />);
    }
}

Now from Parent Component pass unique id to each component. You can also manage id in IFrameComponent.

<IFrameComponent id='1' />
<IFrameComponent id='2' />