admin管理员组文章数量:1414605
To make e2e testing easier I would like to add to each react
ponent data-ponent=
attribute with ponent name. I would like to have it done "automatically" (without adjusting render()
functions everywhere).
Anyone knows how to do it reliably for both class and function based ponents?
To make e2e testing easier I would like to add to each react
ponent data-ponent=
attribute with ponent name. I would like to have it done "automatically" (without adjusting render()
functions everywhere).
Anyone knows how to do it reliably for both class and function based ponents?
Share Improve this question asked Nov 13, 2019 at 11:18 DamaonDamaon 6121 gold badge8 silver badges16 bronze badges 2- It's difficult to give a clear answer without seeing any code. A couple of ideas pop up in my head. First off, to add attributes like that programatically you would need some event to happen like onChange or whatever and then do something like (event) => event.target.setNamedItem('data-ponent'), event.target.getNamedItem(''data-ponent').value = event.target.id (or whatever data is available). A little more info about your problem would be helpful :) – MstrQKN Commented Nov 13, 2019 at 11:36
-
@MstrQKN I need this to be reliable, so need to be on first render and not async events. I simply want to have easy searching via
document.querySelector
for react ponents to aid in writing e2e tests. – Damaon Commented Nov 13, 2019 at 20:00
2 Answers
Reset to default 5- Component name is set via static property
displayName
for each ponent. You need to set it manually. Create hoc (higher order ponent), to wrap ponent with
div
(or any other html tag) which will have required attribute.const withComponentName(WrappedComponent) => { const displayName = WrappedComponent.displayName || WrappedComponent.name || 'UnnamedComponent'; return props => ( <div data-ponent={displayName}><WrappedComponent {...props} /><div> ) }
Wrap all ponent export statements with created hoc.
export default withComponentName(YourShinyComponent)
Another option is to use this Webpack plugin to do it for you:
https://github./lemonmade/babel-plugin-react-ponent-data-attribute
If you're using create-react-app:
If you've ejected already then just follow the docs on the plugin's page ☝️
However, if you have not ejected already, then you can use either of these solutions to customize your build for a create-react-app project:
- https://github./arackaf/customize-cra
- https://github./timarney/react-app-rewired/
本文标签: javascriptReact add data attribute to each render() with component nameStack Overflow
版权声明:本文标题:javascript - React add data attribute to each render() with component name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745159291a2645364.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论