Material UI Popover is thrown to the top left when used on an inline button in a table with a unique key

核能气质少年 提交于 2021-02-10 14:12:15

问题


I'm having some issues when using shortid or any other unique uid generator. The moment I use shortid.generate() as key in a table, the anchor point of my Material UI Popover is thrown to its default position rather than appearing where the button is.

Here's a sandbox! - try removing/adding back shortid.generate() from line 72.

I even tried uniqueId from lodash and the same thing happens - not using a key does render the dialog on the right place though. I even changed versions of Material UI/React and nothing happened.

Any ideas?

Thanks!

EDIT - I usually use item.uid as key since I always fetch items from a service, but if I just created the object, item.uid is undefined - what I did until now was to set item.uid = shortid.generate() (a temporary uid) when I create the object and then just leave <TableRow key={item.uid}> as is. But then I have to remove the temporary uid before I save the object.


回答1:


You should never use random ids as keys (at least not random ids generated during render).

When your state changes (e.g. due to handleClick) your table rows will all be re-rendered with new keys. This means that instead of a simple re-render, all of the table rows will be unmounted and new DOM elements mounted. The anchorEl in your state will point at an element that has been removed from the DOM, so its position cannot be determined.

If you don’t have unique keys related to your data, then just use an index as a key so that it is at least stable across renders (so long as you aren’t adding/removing rows). Another option would be to generate the unique ids when creating your data instead of during rendering.



来源:https://stackoverflow.com/questions/56235483/material-ui-popover-is-thrown-to-the-top-left-when-used-on-an-inline-button-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!