Search code examples
htmlreactjsref

'ref' declaration in pure react


I was taking the redux course on egghead.io by Dan abramov,he create a input field and assigned a ref attribute which seems like a functional assignment.The code follows as ,

<input ref={node => {input = node;}} />
    
<button onClick={() => { input.value = ''}> ADD</button>

Can you please explain this,Thanks in advance!


Solution

  • This is a feature called callback refs. If you pass a function to ref, it will be called with the DOM element as argument and you can do whatever you want with it. In your example that element is assigned to the input variable.

    There are cases where you have to "escape" the React model and need access to the underlying DOM elements (e.g. for controlling focus), and refs are a (the?) way to do that.