Marcus Whybrow
Marcus Whybrow

Reputation: 19998

Rendering as a function of DOM state

Imagine a react component that renders an absolutely positioned element. This element's position on the page is a function of data extracted from the DOM (not from any component state).

Does react have a good pattern for rendering as a function of DOM state?


My best idea I'd call double rendering:

  1. Read the DOM in the relevant componentDidMount/componentDidUpdate.
  2. setState of the dependent component or otherwise re-render it.
  3. Requires defining shouldComponentUpdate to prevent infinite render/componentDidMount loops.

Upvotes: 3

Views: 126

Answers (1)

BentOnCoding
BentOnCoding

Reputation: 28158

The componentDidMount event is where you would want to do this.

componentDidMount - from the react docs

At this point in the lifecycle, the component has a DOM representation which you can access via React.findDOMNode(this).

If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.

I would place the absolute element on the page but out of view, and then move it into position in the componentDidMount event.

I wouldn't call this double rendering.

Upvotes: 4

Related Questions