简体   繁体   中英

Get the component width in render method ReactJS

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM