jcassee
jcassee

Reputation: 71

How to trigger an event after any (re)render of a React/Redux app

A React/Redux app that I develop needs to live inside an iframe. The surrounding document can be told to resize the iframe by sending a message from within. I would like to send the resize message any time the DOM changes.

Using a generic MutationObserver will cause a flickering between the time the DOM is updated and the resizing of the iframe.

The application is set up using

render(
  <Provider store={store}>
    ...
  </Provider>,
  document.querySelector("..."),
  resizeIframe
);

The resizeIframe callback function solves the initial rendering, but does not help with child component updates.

How can I trigger resizeIframe on any React (re)rendering?

Edit: I know resizing on every rendering is inefficient. However, getting rid of the delay between DOM resize and iframe resize appears to be the bigger problem.

Upvotes: 2

Views: 3627

Answers (2)

timetowonder
timetowonder

Reputation: 5461

One of the fundamental ideas of react is that calling calling a render method of an element doesn't necessarily change the DOM.

So it doesn't sound like a good idea to respond to every component's render method being called.

You also wrote:

I would like to send the resize message any time the DOM changes

This doesn't sound great, either: changes to the DOM do not necessarily change the size of the document.

It looks like what you need is to detect the size changes to the iframe that your app lives in, or to the root element of your app. A good idea would be to use a library which does exactly this: https://github.com/wnr/element-resize-detector

Start by playing with its convenient listenTo method:

import elementResizeDetectorMaker from 'element-resize-detector';

const erd = elementResizeDetectorMaker();
erd.listenTo(document.getElementById("test"), function(element) {
  resizeIframe(); // the function you implemented earlier
});

Upvotes: 1

Naveed Aheer
Naveed Aheer

Reputation: 1825

You can use componentWillReceiveProps() to do anything you want when props/state changes. more about react lifecycles

Upvotes: 1

Related Questions