Azimi
Azimi

Reputation: 47

How to get access to CSS values from a styled component (React)?

I want to access the CSS values I assigned to a styled component in a function. How would I do so?

For example:

const Hello = styled.p `
   font-size: 10px;
`;


getFontSize = () => {

}

I want to log the font size of the component Hello in the function getFontSize(). I have tried using refs and InnerRefs but no luck.

Upvotes: 4

Views: 4441

Answers (1)

Tholle
Tholle

Reputation: 112777

You can use the innerRef prop on your component to get a reference to the DOM node, and then use window.getComputedStyle on the node to get the font-size.

Example

const Hello = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
  font-size: 10px;
`;

class Form extends React.Component {
  ref = null;

  componentDidMount() {
    this.getFontSize();
  }

  getFontSize = () => {
    console.log(
      window.getComputedStyle(this.ref, null).getPropertyValue("font-size")
    );
  };

  render() {
    return <Hello innerRef={ref => (this.ref = ref)} />;
  }
}

Upvotes: 4

Related Questions