Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation: useScreenClass with elementRef does not recalculate when ref is set #176

Open
ArthurClemens opened this issue May 30, 2021 · 0 comments

Comments

@ArthurClemens
Copy link

The docs give this example:

function Example2() {
  const elementRef = useRef(null);
  const screenClass = useScreenClass(elementRef);
  return (
    <div ref={elementRef}>...</div>
  );
}

This assumes that screenClass is calculated based on the element width, but that only works after an update (for example screen resize), because setting a ref does not rerender the component.

The result is that on first render the screenClass is off.

Instead use this approach:

function Example2() {
  const elementRef = useRef();
  const [, _setRefElement] = useState();

  const setRefElement = (ref) => {
    if (!elementRef.current) {
      elementRef.current = ref;
      _setRefElement(ref);
    }
  };

  const screenClass = useScreenClass(elementRef);

  return (
    <div ref={setElementRef}>...</div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant