I'm learning react-redux from the docs and don't see what the below means. What is the ref part referring to? And node? This ref isn't used anywhere from I see. Does the ref refer to the child component's node (the input) on the DOM after it gets rendered? If so, why not just refer to the input directly?
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
export default AddTodo
React Refs allow us to reference a DOM element or a class component from within a parent component. This gives us the ability to modify or change that element. Think of refs as a direct connection between components and DOM elements or class components and their parent components.
The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property.
It’s really common to include more than one node to encapsulate more logic around the view behavior. The issue now is that passing a ref to this component will return its instance, a React component reference, and not the input element we want to focus on, like in our first example.
Well, that depends on the type of node the ref attribute is passed to — it’s always different. 1.) When the ref attribute is passed to an HTML element, the ref object receives the underlying DOM element as its current property. 2.)
This is a ref callback attribute, and its purpose is to gain "direct access" to the DOM element/class components. Using a ref you may focus
an input box, get it's value directly or access a method of class component.
In this case it's purpose is to get/change the input's value, by assigning a reference to the input variable (the let input
) - see comments in code.
let AddTodo = ({ dispatch }) => {
let input // the input variable which will hold reference to the input element
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) { // using the input variable
return
}
dispatch(addTodo(input.value)) // using the input variable
input.value = ''
}}>
<input ref={node => {
input = node // assign the node reference to the input variable
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With