Skip to main content

useImperativeHandle

Check out the official React docs!

For more detailed information about React concepts and APIs, please refer to the official documentation for useImperativeHandle.


useImperativeHandle lets you customize the instance value that is exposed when using ref with a component. This is useful for exposing imperative methods to parent components.

This hook is useful when you want to expose imperative methods (like focus) from a child component to its parent, while keeping the internal implementation encapsulated.


[<ReactComponent(true)>]
let Component(inputRef: IRefValue<obj option>) =

React.useImperativeHandle(inputRef, (fun () ->
// return an object with the methods you want to expose
), [||])
// ...

Show code
module Example.UseImperativeHandle

open Feliz

open Fable.Core.JsInterop

type FancyInputController = {|
focus: unit -> unit
|}

[<ReactComponent>]
let FancyInput(inputRef: IRefValue<FancyInputController option>) =
let localRef = React.useInputRef()
React.useImperativeHandle(inputRef, (fun () ->
{| focus = fun () ->
match localRef.current with
| Some el -> el?focus()
| None -> ()
|} |> Some
), [||])
Html.input [
prop.ref localRef
prop.type'.text
prop.placeholder "Type something..."
]

[<ReactComponent(true)>]
let UseImperativeHandle() =
let fancyInputRef = React.useRef(None)
Html.div [
FancyInput fancyInputRef
Html.button [
prop.text "Focus the input"
prop.onClick (fun _ ->
match fancyInputRef.current with
| Some api -> api.focus()
| None -> ()
)
]
]