Regex to find React JSX element with a given property?

I’m doing an audit in a large codebase, and I need to search to find all uses of a component where it is used with a given prop. I’m thinking a regex could be useful here, but I can’t figure out how to handle potential newlines in the markup. I need to be able to differentiate between these two usages, finding the latter:

<Component
  prop1="value1"
  prop2={2}
/>

<Component
  prop1="value1"
  targetProp={3}
  prop2={2}
/>

I don’t care about the value of the target prop, just that it exists on the component.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

<Component(s|n)[^>]*?property

This one support line break.

Method 2

Here’s a regex that should work:

<Components[^>]*?targetProp={[^>]*?/>

This matches:

  • <Component literally, with a s whitespace character to avoid capturing <ComponentWithALongerName
  • [^>] any character that’s not >, zero or more times, lazily
  • targetProp={ literally (adjust if needed for boolean/string values)
  • [^>] any character that’s not >, zero or more times, lazily
  • /> literally


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x