Skip to content

Instantly share code, notes, and snippets.

@geddski
Created November 16, 2019 21:08
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save geddski/5afca746974192a60b5a1bb9c4b935d8 to your computer and use it in GitHub Desktop.
StretchTitle component
/** @jsx jsx */
import { css, jsx } from '@emotion/core'
import React, {useRef, useEffect, useState, useLayoutEffect} from "react"
import useComponentRect from "shared/hooks/useComponentRect"
const StretchTitle = (props) => {
const containerRef = useRef();
const textRef = useRef();
const componentRect = useComponentRect(containerRef, 10);
const [scale, setScale] = useState(1);
const [height, setHeight] = useState();
// calculate how much to scale the text by till it fits its container,
// accounting for any scale already applied
useLayoutEffect(() => {
if (!componentRect) {
return;
}
const textRect = textRef.current.getBoundingClientRect();
let newScale = componentRect.width / (textRect.width / scale);
// limit scale to maxScale
if (props.maxScale && props.maxScale < newScale){
newScale = props.maxScale;
}
setScale(newScale);
}, [containerRef, textRef, componentRect]);
// update the height of the container when the scale changes
useLayoutEffect(() => {
const newTextRect = textRef.current.getBoundingClientRect();
setHeight(newTextRect.height);
}, [scale])
return (
<div ref={containerRef} css={css`
height: ${height}px;
width: 100%;
`}>
<span
ref={textRef}
css={(theme) => css`
display: inline-block;
white-space: nowrap;
transform-origin: top left;
transform: scale(${scale});
`}
>{props.children}</span>
</div>
);
}
export default StretchTitle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment