4

I need to get a width of html element, using React JS. When I do console.log(this.widthPromoLine) in componentDidMount(), it works, but when I do this.setState({moveContent: this.widthPromoLine}), it doesn't.

import React from 'react'
import './index.css'

class Promo extends React.Component {


    constructor(props){
        super(props)
        this.state = {
            moveContent: 0
        }
    }
    
    componentDidMount(){
        this.setState({moveContent: this.widthPromoLine})
    }
    
    render(){
      return <div 
                className="promo-content" 
                ref={promoLine => this.widthPromoLine = promoLine.clientWidth}> 
             </div>
    }


}
.promo-content {
  width: 1870px;
}
dhwind
  • 127
  • 1
  • 9
  • Does this answer your question? [How to get the width of a react element?](https://stackoverflow.com/questions/43817118/how-to-get-the-width-of-a-react-elementt) – wentjun Jun 13 '20 at 21:03

2 Answers2

4

Access the clientWidth after the ref has been assigned to the variable this.widthPromoLine in componentDidMount and then set it like below. Also setState is async, so you need to do anything after the state has been updated in the callback of setState.

import React from "react";
import "./styles.css";

class Promo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      moveContent: 0
    };
  }

  componentDidMount() {
    this.setState({ moveContent: this.widthPromoLine.clientWidth }, () => {
      console.log(this.state);
    });
  }

  render() {
    return (
      <div
        className="promo-content"
        ref={promoLine => (this.widthPromoLine = promoLine)}
      />
    );
  }
}

Hope this helps !

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
1

You can get the width of content using it classname as follow.

let width = document.querySelector(".promo-content").offsetWidth;

And after that update the state,

this.setState({moveContent: width})
Engincan Veske
  • 1,300
  • 1
  • 10
  • 16