35
44

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 1 year has passed since last update.

【React / Next】onClickがクリックしなくても描画時に実行されてしまう

Last updated at Posted at 2022-04-22

onClickイベントに引数のある関数をセットしていたところ、クリックをしていないのに、描画時に実行されてしまうケースを経験したので、その解決方法の議事録です。

結論

公式に記載がありました。

  • onClick={someFunc} のように()を使わない
  • onClick={() => someFunc(arg)} のように関数でラップする

NGコード

export const Parent = () => {
	const handleClick(id: UUID) {
		//
	}

	return (
		<Children handleClick={handleClick} />
	)
}
interface Props {
	handleClick: Function;
}

export const Children = (props: Props) => {
	// functionを()で実行してしまう
	return (
		<Button onClick={props.handleClick(id)}>Click</Button>
	)
}

OKコード

export const Parent = () => {
	const handleClick(id: UUID) {
		//
	}

	return (
		<Children handleClick={handleClick} />
	)
}
interface Props {
	handleClick: Function;
}

export const Children = (props: Props) => {
	return (
		<Button onClick={() => props.handleClick(id)}>Click</Button>
	)
}

文献

35
44
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
35
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?