LoginSignup
4
3

More than 1 year has passed since last update.

React: useRefで参照したinputから同じformのsubmitボタンを辿る

Last updated at Posted at 2021-09-15

ReactでuseRefで参照したinputから同じformのsubmitボタンを辿って別コンポーネントからsubmitボタンをクリックするメモ

——formのref(例えばformRefという名前)を渡して、formRef.submit()すると、ページ更新されてしまうのでsubmitボタンをクリックすることにした。なにかいい方法がある気はするが、とりあえず回避策——

ComponentBからComponentAのformをSubmitする。但し渡すのはinputのrefとする。つまり、ComponentBからinputに値をセットしてからSubmitしたい。

"form" と Element ID で辿れる。

ComponentA
export default function ComponentA(props) {
  const inputTextRef = useRef()

  const onSubmit = (e) => {
    e.preventDefault()
    ...何かの処理...
  }

  return (
    <form onSubmit={ onSubmit }>
      <input type="text" ref={ inputTextRef } />   {/* <-- refを取るのはinput要素とする */}
      <button type="submit" id="submitButton">Submit</button>   {/* <-- idを設定 */}
    </form>
    <ComponentB inputTextRef={ inputTextRef } />
  )
}
ComponentB
export default function ComponentB(props) {

 const submitWithValue = (e) => {
    e.preventDefault()
    props.inputTextRef.current.value = "Special Value"   // <-- ref参照先を更新
    props.inputTextRef.current.form.submitButton.click() // <-- 同じformのsubmitボタンをこんなふうにたどれる
 }

 return (
   <button onClick={ submitWithValue } >Submit ComponentA with a special value</button>
 )
}
4
3
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
4
3