0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】波紋が広がるボタンを実装する

Last updated at Posted at 2021-09-26

概要

ホバーするとマウス位置から波紋が広がるボタンを実装します。
CSS in JSとして、emotion/cssを使用します。

output(video-cutter-js.com) (5).gif

本記事は、以下の動画を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)にマウス位置をセットしています。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?