Kernel James
Kernel James

Reputation: 4064

How do I get size of child so I can center it in ReactJS?

I want to center an absolutely positioned DIV in ReactJS whose textual contents will change.

function Center(props) {
  const divRef = useRef(null);
  const [width, setWidth] = useState();
  const offset = -width/2;

  useEffect(() => {
    if(divRef.current) setWidth(divRef.original.offsetWidth);
  }, []);

  return <div ref={divRef} style={{left: props.x + offset}}>{props.message}</div>
}

I'm stuck on how to get the size of the DIV after the contents of the DIV has changed, so that I can center it by setting the style left/right.

  1. I can't hook into window.onresize because the size of the DIV has nothing to do with the window size and all to do with the text content.

  2. This is a simplified example and the actual example is more complicated, so I cannot use pure CSS layout to center it. I must assign style.left in pixels to accomplish it.

  3. I can get the width at the initial render, but I need the width to be updated every time the text changes.

Upvotes: 0

Views: 80

Answers (1)

justpen
justpen

Reputation: 296

You can use divRef.current.getBoundingClientRect() (getBoundingClientRect) to get the size of an element.

Edit: The answer is to add props.message to the dependency array of useEffect. This will execute the code in useEffect (used to calculate the width) everytime when props.message changes instead of only on the initial render. See comments on this answer.

Upvotes: 0

Related Questions