I'm working with React (version 15.4.2), and I'm populating a <ul>
dynamically with query results from my database. I thought that I had set up the 'key' property on the <li>
s correctly, but evidently I have not - when the list renders, I get the error:
Warning: li: 'key' is not a prop. Trying to access it will result in 'undefined' being returned. If you need to access the same value within the child component, you should pass it as a different prop.
Here's the code for my list:
function UserList(props) { return( <ul className="UserList"> { props.user_list.map((user) => ( <li className="UserListItem" key={user.id}> <Link to={`/users/${user.id}`}>{user.first_name} {user.last_name}</Link> </li> )) } </ul> ); }
I took a look at the docs, and it seems to me like this should be correct. If anyone could clarify my mistake, it would be much appreciated.
Note: Keys are not the same as props, only the method of assigning “key” to a component is the same as that of props. Keys are internal to React and can not be accessed from inside of the component like props.
The warning " key is not a prop. Trying to access it will result in undefined being returned" is caused when we try to access the key prop of a component in React. To solve the error, pass a prop with a different name to your component. Here is an example of how the warning is caused.
React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.
To specify null prop type in React, we can set null as the default prop value. We create the MyComponent component accepts the item prop. We set item 's type to be a string and is required. And then we specify that its default value is null so it can be set to null when nothing is set for item .
Somewhere else in the code you're trying to access props.key
Basically, "key" props are not passed to a child component.
React docs say: "special props (ref and key) are used by React, and are thus not forwarded to the component.".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With