<div id="root"></div>
body {
overflow: hidden;
}
.container {
width: 100%;
height: 100vh;
background-color: #212121;
}
const useCenterPosition = (childSize, parentSize) => {
const [x, setX] = React.useState(0);
const [y, setY] = React.useState(0);
React.useEffect(() => {
const { width: outerWidth, height: outerHeight } = parentSize;
const { width: innerWidth, height: innerHeight } = childSize;
setX((outerWidth - innerWidth) / 2);
setY((outerHeight - innerHeight) / 2);
}, [childSize, parentSize]);
return [
x, y,
];
};
const Child = ({ parentWidth, parentHeight }) => {
// let's say we know child's size already
const width = 200;
const height = 200;
const [posX, posY] = useCenterPosition(
{ width, height },
{ width: parentWidth, height: parentHeight },
);
return (
<svg
width={width}
height={height}
x={posX}
y={posY}
>
<rect fill="cornflowerblue" x={0} y={0} width={width} height={height} />
</svg>
);
};
const Parent = () => {
const [currentWidth, setCurrentWidth] = React.useState(0);
const [currentHeight, setCurrentHeight] = React.useState(0);
const handleRef = React.useCallback(instance => {
const { width, height } = instance.getBoundingClientRect();
setCurrentWidth(width);
setCurrentHeight(height);
}, [setCurrentWidth, setCurrentHeight]);
return (
<svg
width="100%"
height="100%"
ref={handleRef}
>
<Child
parentWidth={currentWidth}
parentHeight={currentHeight}
/>
</svg>
);
};
const Container = () => (
<div className="container">
<Parent />
</div>
);
ReactDOM.render(
<Container />,
document.getElementById('root'),
);
View Compiled
This Pen doesn't use any external CSS resources.