Description
ref: https://github.com/reactpatterns/reactpatterns-website/blob/main/docs/accessing-a-child-component.md
Please consider adding this text to help explain everything that's going on in the example:
Explanation
In SignInModal, render
is executed. The Input
component's ref
attribute is executed as a function, accepting the current component
, which is the Input
component itself. The function does not return a value. It uses this
, which is scoped to SignInModel to create a new property, InputComponent
, and it assigns the Input
component to that new property.
When render()
executes, the new Input
component is created, with its this.textInput
assigned the result of createRef()
. The component render()
is executed and the input
element's ref
attribute is assigned the new reference. Therefore, in Input, textInput refers to the input
element as a child component.
Back in SignInModal, in componentDidMount
, this.InputComponent
is available, as created in the render. The focus()
method is executed on that property, which is the Input
component. The focus()
method uses its this.textInput
property, a reference to the 'input' element, to set the element's focus.