zappee
zappee

Reputation: 22726

pass "key" param to react component

I am trying to pass a parameter with name "key" to a react component and it does not work. If i use "keyy" instead of "key" then it works.

It seems for me that "key" is a restricted keyword and I can not use it as a name of parameter.

Is that true?

That is my example:

render() {
   <MyComponent key='apple'
                keyy='pear'>
}

Upvotes: 16

Views: 20430

Answers (3)

prosti
prosti

Reputation: 46419

key is a reserved word.

From here:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.

This is also good and explains why React uses the key param, and what are the benefits. You will find that the key param is the cornerstone of the React reconciliation algorithm.


Apart from the key param there are few more reserved words you should not use such as:

ref and dangerouslySetInnerHTML

The later one dangerouslySetInnerHTML you use instead of DOM innerHTML

Check in here for more details.

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104479

Yes key keyword is reserved, this is used by React to identify html elements, it should be unique. It helps to improve the performance. We should add a key to each child. This way React can handle the minimal DOM change.

From React Docs:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Keys used within arrays should be unique among their siblings. However they don't need to be globally unique. Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name.

Upvotes: 5

Lyubomir
Lyubomir

Reputation: 20037

Yes, that is true, key is a restricted keyword and doesn't get propagated as props.


Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);

With the example above, the Post component can read props.id, but not props.key.

Read more in the docs

Upvotes: 26

Related Questions