Skip to content

Commit

Permalink
use useImperativeHandle to share Refs (#1014)
Browse files Browse the repository at this point in the history
  • Loading branch information
decovicdev authored Sep 19, 2023
1 parent c16a084 commit ad8f642
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions src/content/faqs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ React Hook Form needs a `ref` to collect the input value. However, you may want
<TabGroup buttonLabels={["TS", "JS"]}>

```typescript copy
import React, { useRef } from "react"
import { useRef, useImperativeHandle } from "react"
import { useForm } from "react-hook-form"

type Inputs = {
Expand All @@ -137,48 +137,49 @@ type Inputs = {

export default function App() {
const { register, handleSubmit } = useForm<Inputs>()
const firstNameRef = useRef<HTMLInputElement | null>(null)
const onSubmit = (data) => console.log(data)
const firstNameRef = useRef<HTMLInputElement>(null)
const onSubmit = (data: Inputs) => console.log(data)
const { ref, ...rest } = register("firstName")
const onClick = () => {
firstNameRef.current!.value = ""
}

useImperativeHandle(ref, () => firstNameRef.current)

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...rest}
name="firstName"
ref={(e) => {
ref(e)
firstNameRef.current = e // you can still assign to ref
}}
/>

<input {...rest} ref={firstNameRef} />
<button type="button" onClick={onClick}>
clear
</button>
<button>Submit</button>
</form>
)
}
```

```javascript copy
import React, { useRef } from "react"
import { useRef, useImperativeHandle } from "react"
import { useForm } from "react-hook-form"

export default function App() {
const { register, handleSubmit } = useForm()
const firstNameRef = useRef(null)
const onSubmit = (data) => console.log(data)
const { ref, ...rest } = register("firstName")
const onClick = () => {
firstNameRef.current!.value = ""
}

useImperativeHandle(ref, () => firstNameRef.current)


return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...rest}
name="firstName"
ref={(e) => {
ref(e)
firstNameRef.current = e // you can still assign to ref
}}
/>

<input {...rest} ref={firstNameRef} />
<button type="button" onClick={onClick}>
clear
</button>
<button>Submit</button>
</form>
)
Expand Down

1 comment on commit ad8f642

@vercel
Copy link

@vercel vercel bot commented on ad8f642 Sep 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

react-hook-form-website – ./

react-hook-form.com
react-hook-form-website-git-master-hook-form.vercel.app
react-hook-form-website-hook-form.vercel.app

Please sign in to comment.