Home > Net >  Find Color of Text Element in React
Find Color of Text Element in React

Time:10-05

I have a Link component and I want to find out what the color of the text is. How would I do that in React?

I know with Vanilla JS, you can find it with element.style.color however if I perform similar with below code using textEl.style.color I get undefined.

export function TextLink({ children, path, inline = false, dash = false }: TextLinkProps) {
  const textEl = useRef("");
  return (
    <StyledLink href={path} inline={inline} dash={dash} ref={textEl}>
      {children}
    </StyledLink>
  );
}

CodePudding user response:

You can use window.getComputedStyle() and pass the element itself by its ref like so:


const ref = React.useRef();
...
...
...

React.useEffect(() => {
  const style = window.getComputedStyle(ref.current)
  console.log(style.color); // rgb(255, 0, 0) 
}, []);

Window.getComputedStyle()

CodePudding user response:

Gives rgb(0, 0, 0) to me

const textEl = React.useRef(null);

  React.useEffect(() => {
    if (textEl.current) {
      console.log(window.getComputedStyle(textEl.current).color)
    }
  }, [textEl])

Or simply just use textEl.current.style.color if you don't need computed one

CodePudding user response:

You are forgetting the 'current' with your reference. write it like this :

textEl.current.style.color
  • Related