Ad

Get The Component Width In Render Method ReactJS

- 1 answer

I need to know component's width in render method, but getting DOM elements in render method is not possible. Solving problem I found this article. The problem in article is the same as mine.

Solution:

  1. save component's width to state in componentDidMount method.
  2. subscribe to window resize event and update state.

So I can get component width from component's state.

Anybody knows another approach to solve this problem? Thanks.

Ad

Answer

Well, you don't have to save the width in state, you could grab it each time with ReactDOM.findDOMNode(), but this is about the best you're going to get. You can't update in render for two reasons:

  1. your DOM elements are currently being rendered but don't exist yet
  2. Even if they did, triggering an update in render is an easy way to trigger an infinite render loop.

Tldr: Just go with the method you have, that works just fine

Ad
source: stackoverflow.com
Ad