6

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.

dangerismycat
  • 824
  • 2
  • 11
  • 18

3 Answers3

16

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

This one support line break.

Sarawut Positwinyu
  • 4,974
  • 15
  • 54
  • 80
  • Agreed, your solution is better! Thanks! – dangerismycat Mar 12 '20 at 20:09
  • What if my component looks like this: `} property={1} />` - the regex fails because of the inner ``! Can you create a regex to support that as well? :) – Ziarno Aug 11 '20 at 09:43
  • The given solution unfortunately breaks if it meets a `>` in another Component's property: arrow functions {}} property={1} /> and components as props } property={1} /> Does anyone know if it's possible to enhance the RegExp to keep track of those? – buondevid Nov 05 '21 at 17:27
2

Here's a regex that should work:

<Component\s[^>]*?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
dangerismycat
  • 824
  • 2
  • 11
  • 18
0

The accepted answer is not working when you have component as prop or arrow function (because arrow function has > character)

for example

<Component icon={<Icon />} property={() => ()} />

Use this pattern instead

<Component((?:=>|<[^>]*>|[^>])*)>(.|\n)*$

There is group in regex that I explain (?:=>|<[^>]*>|[^>])*

  1. => If its arrow function we match => and allow >
  2. <[^>]*> If there is another component in props, we allow > only if we have <.
  3. [^>] In the end we accept any character unless its >
Ali Akbar Azizi
  • 3,272
  • 3
  • 25
  • 44