mangocaptain mangocaptain - 3 months ago 28
React JSX Question

What does ref and node refer to in react-redux?

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

Answer

This is a ref callback attribute, and is purpose is to give access to the input value via the input in the let input (see added comments).

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>
  )
}
Comments