Kayote
Kayote

Reputation: 15617

How to read DOM in React

React is uni-directional.

However, there are many cases where we need to 'get' / read DOM, whether it is to get the parent element / or CSS values.

In my case, I have a dynamic width property set on a div, which I want to get in absolute units (px), how does React handle this kind of logic? I have come across suggestions of using 'refs' in React, however, I am not clear whether that is the recommended method.

CSS:
...
width: 60%;
...

Many thanks,

Upvotes: 2

Views: 525

Answers (1)

Dirk-Jan
Dirk-Jan

Reputation: 1149

You are right about using refs, you could also do it with native javascript dom querys but setting a ref for a element is faster.

So basically you set a ref like this:

<div ref="awesome"></div>

Then in your code do something like:

var node = React.findDOMNode(this.refs.awesome);
alert(node.offsetWidth);

Upvotes: 3

Related Questions