Matching React props: strings and expressions #1103
-
Hello! I was trying my hand at writing codemods for React components in Say I want to transform So cases like: - <Component variant="old">Hello</Component>
+ <Component variant="new">Hello</Component> and - <Component variant={condition ? 'old' : 'other'}>Hello</Component>
+ <Component variant={condition ? 'new' : 'other'}>Hello</Component> This was my best shot at this so far: id: update-prop-string
rule:
pattern: <Component $$$PROPS_BEFORE variant="old" $$$PROPS_AFTER>
fix: <Component $$$PROPS_BEFORE variant="new" $$$PROPS_AFTER>
---
id: update-prop-expression
rule:
pattern: <Component $$$PROPS_BEFORE variant={$VARIANT} $$$PROPS_AFTER>
transform:
NEW_VARIANT:
replace:
by: new
replace: '\bold\b'
source: $VARIANT
fix: <Component $$$PROPS_BEFORE variant={$NEW_VARIANT} $$$PROPS_AFTER> My main questions is: Is there a way to condense these into one rule? Or any way to make this cleaner or better in general? Any insight would be appreciated! I realize that second rule would match if a variable is named I was also trying to figure out how to get rid of the extra whitespace character that shows up if there is no Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, I recommend https://dev.to/herrington_darkholme/migrate-to-react-19-with-ast-grep-28op as an example to match JSX attribute. In your case, the rewriter is also a helpful construct to change string literal rule:
all:
- pattern:
context: '<div variant=$A />'
selector: jsx_attribute
- pattern: $ATTR
rewriters:
- id: old-to-new
rule:
kind: string_fragment
regex: '^old$'
fix: new
transform:
NEW_ATTR:
rewrite:
rewriters: [old-to-new]
source: $ATTR
fix: $NEW_ATTR |
Beta Was this translation helpful? Give feedback.
Hi, I recommend https://dev.to/herrington_darkholme/migrate-to-react-19-with-ast-grep-28op as an example to match JSX attribute.
In your case, the rewriter is also a helpful construct to change string literal
"old"
.https://ast-grep.github.io/playground.html#eyJtb2RlIjoiQ29uZmlnIiwibGFuZyI6InRzeCIsInF1ZXJ5IjoiIiwicmV3cml0ZSI6IiIsImNvbmZpZyI6InJ1bGU6XG4gIGFsbDpcbiAgLSBwYXR0ZXJuOiBcbiAgICA…