Home > Mobile >  Why do these seemingly similar props result in different behavior?
Why do these seemingly similar props result in different behavior?

Time:07-19

Question:

  • Why does my WarningMessage component render differently when I pass testFor="custom" instead of "a" or "b" even though my console.log statements seem to suggest it's working identically.
  • I'm especially confused because the console.log statement in renderMessageStyle() suggests it's working correctly in all scenarios (see bottom for example)

Code Sandbox: https://codesandbox.io/s/q4m8mq

Expected behavior:

When I type "c" into the input field it, the warning message should appear after a single keystroke. For an example of proper behavior change testFor="a" in Parent and type "a" into the input field.

How it works:

  • In the Parent component I give a string value to the testFor prop.
  • The testFor prop is passed to the WarningMessage component which uses its value in testForX() to return the proper regex formula.
  • The result is saved to a variable called regEx which acts as a gatekeeper for whether to display the message by running {regEx.test(testWatch) && renderMessageStyle(messageType, message)}

Other notes:

  • testForX can accept the strings "a", "b", or "custom"
  • If "custom" is passed then testForX() sets its return value to the regFormula prop passed from Parent. The regFormula prop is not used otherwise.
  • I'm using useWatch from react-hook-form to monitor input field changes

Display a warning message when a user's input meets certain regex tests when I pass one-off "custom" regex as a prop to the child WarningMessage component.

Example:

const renderMessageStyle = (messageType, message) => {

    // This console statement works for all cases but the switch statement isn't displaying properly

    console.log("renderMessageStyle fired!", testWatch, testFor, regEx);

    switch (messageType) {
      case "warn":
        return (
          <span className="text-sm font-bold text-amber-600 pt-4 pb-2">
            ⚠️ This is a warning message for what you wrote in the input field:{message}
            {message}
          </span>
        );

CodePudding user response:

The problem is that RegExp.prototype.test advances through the text

When you pass it from the parent your testForX is called only once so the regexp is used multiple times. If you don't pass it from the parent, you create a new regexp every time a key is pressed.

It's better to just use String.prototype.match instead as it gives every time the same results.

  • Related