Reputation: 9848
ref and Key both are used for pointing the element.But what is the basic difference between these two?
Upvotes: 2
Views: 3565
Reputation: 1275
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
Upvotes: 1