4

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.

1
  • 1
    Can you share what you tried? Commented Aug 10, 2018 at 16:54

1 Answer 1

4

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)} />;
  }
}
Sign up to request clarification or add additional context in comments.

12 Comments

I tried this but i get "Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'."
@Azimi Do you get that error from the example link in my answer? If you mean in your own code, you must make sure that the component has rendered first so that ref will be set.
yes my component is rendered, i am doing the call in the componentdidmount() function. Im doing it almost identical to how you did it.
@Azimi Alright. You might have missed some tiny detail. Are you assigning ref to this.ref, for example?
i figured out my issue, appreciate the help. Thanks again!
|

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.