3
2

More than 1 year has passed since last update.

【React】eventオブジェクトと他の値を複数取得する(渡す)方法

Last updated at Posted at 2022-10-31

はじめに

  • Reactを触っていたときにイベントハンドラ関数の引数に、propsで渡ってきた引数に加えてeventオブジェクトも渡したい時にどうするか迷ったため、共有します。
    • 想定読者はJSやReactなどのフロント技術を触っている方とします。

追記
この記事で紹介するtodosという値はイベントハンドラ側から引数として渡さなくても、propsから受けとった変数でそのまま使用できたため、誤りな点がありますのでご容赦ください。

実現したいこと

  • イベントハンドラの関数の引数として、eventオブジェクトともう一つ任意の引数の値を渡したい。

前提(準備)

  • 今回はReactでサンプルを動かします。

参考

修正前

  • 修正前では、propsから受け取ったtodosの値が取得できず、
const Form = ({ todos, addedTodo }) => {
//...(略)

	// ここでtodosを取得したい
  const addTodo = (e) => {
    e.preventDefault();

	const newTodo = {
      id: todos.length + 1,
      content: enteredTodo,
    };

    addedTodo(newTodo);
  };

//...(略)
<form onSubmit={addTodo}> 	// eオブジェクトしか(todosは)渡せない
	<button>追加</button>
</form>

修正後

  • アロー関数を定義して、eオブジェクトを引数で渡してから、引数を2つ定義した関数をreturnする。
import { useState } from 'react';

const Form = ({ todos, addedTodo }) => {
  const [enteredTodo, setEnteredTodo] = useState('');

  // eオブジェクトとtodosも取得可能に
  const addTodo = (todos, e) => {
    e.preventDefault();

    const newTodo = {
      id: todos.length + 1,
      content: enteredTodo,
    };

    addedTodo(newTodo);

    setEnteredTodo('');
  };

  return (
      <form
    	// ここでeオブジェクトをアロー関数で渡して、関数の引数で2つの引数を渡す
        onSubmit={(e) => {
          addTodo(todos, e);
        }}
      >
		<button>追加</button>
      </form>
  );
};

export default Form;

終わりに

意外にあまり情報が出てこなかったので、少しハマりました・・・。
参考になれれば幸いです!

3
2
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
3
2