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 theregFormula
prop passed from Parent. TheregFormula
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>
);