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;
}

1

2 Answers 2

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 !

Sign up to request clarification or add additional context in comments.

Comments

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})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.