Last active
March 14, 2022 04:34
-
-
Save crazy4groovy/32420464525c50e1036618b2395a8e70 to your computer and use it in GitHub Desktop.
Shift web components around in small increments. (ReactJS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// No matter how impressive your design system is, there will always be times that small layout adjustments are required. This handy component lets you shift things around in small increments. | |
// credit: https://www.joshwcomeau.com/snippets/react-components/shift-by/ | |
import React from 'react'; | |
function ShiftBy({ x = 0, y = 0, children }) { | |
return ( | |
<div | |
style={{ | |
transform: `translate(${x}px, ${y}px)`, | |
}} | |
> | |
{children} | |
</div> | |
); | |
} | |
export default ShiftBy; | |
/* | |
<ShiftBy x={-3}> | |
<Heading>Slightly Misaligned Heading</Heading> | |
</ShiftBy> | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// credit: https://www.joshwcomeau.com/snippets/react-hooks/use-boop/ | |
import React from 'react'; | |
import { useSpring } from 'react-spring'; | |
// UPDATE this path to your copy of the hook! | |
// Source here: https://joshwcomeau.com/snippets/react-hooks/use-prefers-reduced-motion | |
import usePrefersReducedMotion from '@hooks/use-prefers-reduced-motion.hook'; | |
function useBoop({ | |
x = 0, | |
y = 0, | |
rotation = 0, | |
scale = 1, | |
timing = 150, | |
springConfig = { | |
tension: 300, | |
friction: 10, | |
}, | |
}) { | |
const prefersReducedMotion = usePrefersReducedMotion(); | |
const [isBooped, setIsBooped] = React.useState(false); | |
const style = useSpring({ | |
transform: isBooped | |
? `translate(${x}px, ${y}px) | |
rotate(${rotation}deg) | |
scale(${scale})` | |
: `translate(0px, 0px) | |
rotate(0deg) | |
scale(1)`, | |
config: springConfig, | |
}); | |
React.useEffect(() => { | |
if (!isBooped) { | |
return; | |
} | |
const timeoutId = window.setTimeout(() => { | |
setIsBooped(false); | |
}, timing); | |
return () => { | |
window.clearTimeout(timeoutId); | |
}; | |
}, [isBooped]); | |
const trigger = React.useCallback(() => { | |
setIsBooped(true); | |
}, []); | |
let appliedStyle = prefersReducedMotion ? {} : style; | |
return [appliedStyle, trigger]; | |
} | |
export default useBoop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment