ref and Key both are used for pointing the element.But what is the basic difference between these two?
-
2in short ref is for our use, and key will be for react internal usages. – Mayank Shukla Aug 31 '17 at 11:13
-
1`ref` gives access to the DOM element. Whereas `key` identifies which item has been changed, added or removed. https://facebook.github.io/react/docs/lists-and-keys.html – Hemerson Carlin Aug 31 '17 at 11:14
-
1check these two separate answers for more details about these two, [**ref**](https://stackoverflow.com/questions/29503213/use-state-or-refs-in-react-js-form-components) and [**keys**](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – Mayank Shukla Aug 31 '17 at 11:15
1 Answers
Keys
Keys React are utilised to identify specific Virtual DOM Elements that have changed. The classic example of usage of keys is a list. Let’s imagine we have an array of objects:
fruits = [{name: "Pineapple", id: 1}, {name: "Banana", id: 2}, {name: "Passion Fruit", id: 3}
If we were to pass this array as a prop to a FruitList component in order to render a list of fruits onto the page, we would iterate through our array of fruits, rendering each one as a list item:
const FruitList = (props) =>{
const fruits = props.fruits.map((fruit) =>
<li>{fruit.name}</li>
)
return(
<ul>
{fruits}
</ul>
)
}
You might also find yourself in a situation when items in your array don’t really possess a unique ID. In case of no stable IDs for rendered items, index of iterator may be used as a key.
const FruitList = (props) =>{
const fruits = props.fruits.map((fruit, index) =>
<li key={index}>{fruit.name}</li>
)
return(
<ul>
{fruits}
</ul>
)
}
Refs
Similarly to keys refs are added to elements in the form of attributes. According to React.js documentation some of the best cases for using refs are: managing focus, text selection, or media playback, triggering animations, and integrating with third-party DOM libraries.
Usually props are the way for parent components interact with their children. However in some cases you might need to modify a child without re-rendering it with new props. That’s exactly when refs attribute comes to use.
Both strings and callback functions used to be allowed as values passed into refs, however strings are now considered legacy, and will likely be deprecated at some point in the future. When passing a ref attribute to an HTML element, we pass that very DOM element as an argument to the callback function:
class TextInput extends React.Component {
constructor(props) {
super(props);
this.focusTextInput = this.focusTextInput.bind(this);
}
focusInput() {
this.textInput.focus();
}
render() {
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input }} />
<input
type="button"
value="Focus the text input"
onClick={this.focusInput}
/>
</div>
);
}
}
Source: https://medium.com/@nothingisfunny/keys-and-refs-in-react-fd954457fd75

- 1,245
- 11
- 25