Source:  Twitter logo

I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

componentDidMount()  {
  console.log(this.refs.container.style);     
}


render()  {
   return (
      <div ref={"container"} className={"container"}></div>  //set reff
   );
}

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

Thanks!

For React v <= 15

console.log( ReactDOM.findDOMNode(this.refs.container).style); //React v > 0.14

console.log( React.findDOMNode(this.refs.container).style);//React v <= 0.13.3

EDIT:

For getting the specific style value

console.log(window.getComputedStyle(ReactDOM.findDOMNode(this.refs.container)).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;

For React v>= 16

assign ref using callback style or by using createRef().

assignRef = element => {
  this.container = element;
}
getStyle = () => {

  const styles = this.container.style;
  console.log(styles);
  // for getting computed styles
  const computed = window.getComputedStyle(this.container).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;
  console.log(computed);
}
39 users liked answer #0dislike answer #039
Vikramaditya profile pic
Vikramaditya

Here is an example of computing the CSS property value via React Refs and .getComputedStyle method:

class App extends React.Component {
    constructor(props) {
        super(props)
        this.divRef = React.createRef()
    }

    componentDidMount() {
        const styles = getComputedStyle(this.divRef.current)

        console.log(styles.color) // rgb(0, 0, 0)
        console.log(styles.width) // 976px
    }

    render() {
        return <div ref={this.divRef}>Some Text</div>
    }
}
10 users liked answer #1dislike answer #110
Purkhalo Alex profile pic
Purkhalo Alex

It's worth noting that while ReactDOM.findDOMNode is usable today, it will be deprecated in the future in place of callback refs.

There is a post here by Dan Abramov which outlines reasons for not using findDOMNode while providing examples of how to replace the use of ReactDOM.findDOMNode with callback refs.

Since I've seen SO users get upset when only a link was included in an answer, so I will pass along one of the examples Dan has kindly provided:

findDOMNode(stringDOMRef)

**Before:**

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this.refs.something).scrollIntoView();
  }

  render() {
    return (
      <div>
        <div ref='something' />
      </div>
    )
  }
}
**After:**

class MyComponent extends Component {
  componentDidMount() {
    this.something.scrollIntoView();
  }

  render() {
    return (
      <div>
        <div ref={node => this.something = node} />
      </div>
    )
  }
}
4 users liked answer #2dislike answer #24
flyingace profile pic
flyingace

You should use ReactDOM.findDOMNode method and work from there. Here's the code that does what you need.

var Hello = React.createClass({

componentDidMount: function() {
  var elem = ReactDOM.findDOMNode(this.refs.container);
  console.log(elem.offsetWidth, elem.offsetHeight);    
},

render: function() {
   return (
      <div ref={"container"} className={"container"}>
        Hello world
      </div>
   );
}
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

jsFiddle

3 users liked answer #3dislike answer #33
mtomic profile pic
mtomic

In case of function components use the useRef Hook:

  const _optionsButton = useRef(null);
  const _onSelectText = (event) => {
    if (true) {
      _optionsButton.current.style["display"] = "block";
    } else {
      _optionsButton.current.style["display"] = "none";
    }
    console.log(_optionsButton.current.style); //all styles applied to element
  };

add ref attribute to component

<IconButton
            style={{
              color: "rgba(0, 0, 0, 0.54)",
              fill: "rgba(0, 0, 0, 0.54)",
              border: "1px solid rgba(0, 0, 0, 0.54)",
              position: "absolute",
              display: "none",
            }}
            color="primary"
            component="span"
            onClick={() => {}}
            ref={_optionsButton} //this
          >
            Check
 </IconButton>

Thank you

0 users liked answer #4dislike answer #40
Niket Tongare profile pic
Niket Tongare

You already get the style, the reason why CSSStyleDeclaration object's props have so much empty string value is it's link to the inner style.

See what will happen if you make change like below:

<div ref={"container"} className={"container"} style={{ width: 100 }}></div>

-1 users liked answer #5dislike answer #5-1
David Guan profile pic
David Guan

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).