score:4

Accepted answer

Unfortunately, ReactDOM.hydrate does not attach the onLoad or onError events.

The best method I can think of is doing a sort of 2-pass rendering. From the server, always render the fallback (or a placeholder) image. On the client, use componentDidMount and state to update the image's src to the real source.

export default class Image extends PureComponent {
  state = { isMounted: false }

  componentDidMount() {
    this.setState({ isMounted: true });
  }

  render() {
    return (
      <img
        src={ isMounted ? this.props.src : this.props.fallbackSrc }
        onError={(e) => {  
          e.target.src = this.props.fallbackSrc;
        }}
      />
    );
  }
}

Since the server doesn't call the componentDidMount lifecycle, it will always render the fallback image.

After the hydrate completes and the component is mounted, it will update the state triggering a rerender that will then use the real src from props.


Related Query

More Query from same tag