What is @svgr/babel-plugin-add-jsx-attribute?
@svgr/babel-plugin-add-jsx-attribute is a Babel plugin designed to add specific JSX attributes to SVG elements. This is particularly useful when working with SVGs in React projects, as it allows for the automatic addition of attributes like className, style, or any other custom attribute to SVG elements during the build process.
What are @svgr/babel-plugin-add-jsx-attribute's main functionalities?
Add Static Attribute
This feature allows you to add a static attribute to specified SVG elements. In this example, a className attribute with the value 'my-svg-class' is added to all <svg> elements.
module.exports = {
plugins: [
[
'@svgr/babel-plugin-add-jsx-attribute',
{
elements: ['svg'],
attributes: [{ name: 'className', value: 'my-svg-class' }]
}
]
]
};
Add Dynamic Attribute
This feature allows you to add dynamic attributes to specified SVG elements. In this example, a data-id attribute with a dynamic value '{id}' is added to all <svg> elements.
module.exports = {
plugins: [
[
'@svgr/babel-plugin-add-jsx-attribute',
{
elements: ['svg'],
attributes: [{ name: 'data-id', value: '{id}' }]
}
]
]
};
Add Multiple Attributes
This feature allows you to add multiple attributes to specified SVG elements. In this example, both className and role attributes are added to all <svg> elements.
module.exports = {
plugins: [
[
'@svgr/babel-plugin-add-jsx-attribute',
{
elements: ['svg'],
attributes: [
{ name: 'className', value: 'my-svg-class' },
{ name: 'role', value: 'img' }
]
}
]
]
};
Other packages similar to @svgr/babel-plugin-add-jsx-attribute
babel-plugin-react-svg
babel-plugin-react-svg is a Babel plugin that allows you to import SVG files as React components. While it does not specifically add JSX attributes, it provides a way to use SVGs directly in React components, which can then be manipulated with JSX attributes.
babel-plugin-inline-react-svg
babel-plugin-inline-react-svg is another Babel plugin that inlines SVGs as React components. Similar to babel-plugin-react-svg, it does not add JSX attributes directly but allows for SVG manipulation within React components.
react-svg-loader
react-svg-loader is a Webpack loader that transforms SVGs into React components. It allows for the addition of JSX attributes through React props, providing a similar end result to @svgr/babel-plugin-add-jsx-attribute.
@svgr/babel-plugin-add-jsx-attribute
Install
npm install --save-dev @svgr/babel-plugin-add-jsx-attribute
Usage
.babelrc
{
"plugins": [
[
"@svgr/babel-plugin-add-jsx-attribute",
{
"elements": ["svg"],
"attributes": [
{
"name": "width",
"value": "200",
"spread": false,
"literal": false,
"position": "end"
}
]
}
]
]
}
License
MIT