概要
ホバーするとマウス位置から波紋が広がるボタンを実装します。
CSS in JSとして、emotion/cssを使用します。
本記事は、以下の動画をReactに変換したものです。(ほぼ写経です)
emotion/css の使い方をおおまかに知りたい方は、以下を参照してください。
実装
.tsx
import React, { useRef, VFC } from 'react';
import { css } from '@emotion/css';
export const ButtonRipple: VFC = () => {
const btnRef = useRef<HTMLAnchorElement>(null)
const mousemoveHandler = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
const x = e.pageX - btnRef.current!.offsetLeft
const y = e.pageY - btnRef.current!.offsetTop
btnRef.current!.style.setProperty('--x', x + 'px')
btnRef.current!.style.setProperty('--y', y + 'px')
}
return (
<div className={styles.container}>
<a ref={btnRef} className={styles.btn} href="/" onMouseMove={mousemoveHandler}>
<span className={styles.text}>Button</span>
</a>
</div>
)
}
const styles = {
container: css`
position: relative;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #222;
`,
btn: css`
position: relative;
display: inline-flex;
padding: 1.5em 5em;
background-color: #363636;
text-decoration: none;
letter-spacing: 1px;
overflow: hidden;
&::before {
content: '';
position: absolute;
top: var(--y);
left: var(--x);
transform: translate(-50%, -50%);
width: 0;
height: 0;
border-radius: 50%;
background-color: #2196f3;
transition: width 0.5s, height 0.5s;
}
&:hover::before {
width: 300px;
height: 300px;
}
`,
text: css`
position: relative;
color: #fff;
font-size: 2rem;
z-index: 1;
`
}
onMouseMoveイベントで、setProperty
を使って、CSS変数(--x・--y)にマウス位置をセットしています。