Rename SVG Attribute Has Fix
Description
SVG(Scalable Vector Graphics)s' hyphenated names are not compatible with JSX syntax in React. JSX requires camelCase naming for attributes. For example, an SVG attribute like stroke-linecap
needs to be renamed to strokeLinecap
to work correctly in React.
YAML
yaml
id: rewrite-svg-attribute
language: tsx
rule:
pattern: $PROP # capture in metavar
regex: ([a-z]+)-([a-z]) # hyphenated name
kind: property_identifier
inside:
kind: jsx_attribute # in JSX attribute
transform:
NEW_PROP: # new property name
convert: # use ast-grep's convert
source: $PROP
toCase: camelCase # to camelCase naming
fix: $NEW_PROP
Example
tsx
const element = (
<svg width="100" height="100" viewBox="0 0 100 100">
<path d="M10 20 L30 40" stroke-linecap="round" fill-opacity="0.5" />
</svg>
)
Diff
ts
const element = (
<svg width="100" height="100" viewBox="0 0 100 100">
<path d="M10 20 L30 40" stroke-linecap="round" fill-opacity="0.5" />
<path d="M10 20 L30 40" strokeLinecap="round" fillOpacity="0.5" />
</svg>
)
Contributed by
Inspired by SVG Renamer