This is a small Babel plugin for adding data attributes to React JSX elements. I created this plugin to add meaningful identifiers for styled components. This allows our components to have a designated attribute for end-to-end integration tests (without having to add them manually).
<div class="Page-jLerck lhFHrB">
<div class="Header-dJBcYZ dqmObD">...</div>
<div class="Body-MnRsT gzvZiS">...</div>
</div>
<div class="Page-jLerck lhFHrB" data-test="Page">
<div class="Header-dJBcYZ dqmObD" data-test="Header">
...
</div>
<div class="Body-MnRsT gzvZiS" data-test="Body">
...
</div>
</div>
This package is available on npm as babel-plugin-react-add-property
, and you can find it
here.
To install the latest stable version with Yarn:
$ yarn add --dev babel-plugin-react-add-property
...or with npm:
$ npm install babel-plugin-react-add-property
.babelrc
(Recommended)If you don't provide a property name, the attribute name will default to data-test
.
NOTE: As these attributes are intended only for testing purposes, we're telling Babel to only use the plugin in our development environment. If you'd like to use this plugin in other environments, you'll need to specify them as well.
// .babelrc
{
"env": {
"development": {
"plugins": ["react-add-property"]
}
}
}
However, if you'd like to have a custom attribute name, you can pass it in with your .bablerc
.
// .babelrc
{
"env": {
"development": {
"plugins": [["react-add-property", { "property": "data-qa" }]]
}
}
}
This custom config would transform this div:
<div class="Header-dJBcYZ dqmObD">...</div>
to look like this:
<div class="Header-dJBcYZ dqmObD" data-qa="Header">
...
</div>
babel --plugins react-add-property script.js
without options:
require('babel-core').transform('code', {
plugins: ['react-add-property'],
});
with options:
require('babel-core').transform('code', {
plugins: [['react-add-property', { property: 'data-qa' }]],
});
I am thankful for any contributions made by the community. By contributing you agree to abide by the Code of Conduct in the Contributing Guidelines.