Forcing reevaluation of child component

Viewed 100

I have a form that uses custom <Input> elements. In the Input component I manage the state of the input (valid/invalid). In the form I ask the user to re-enter the password and I would like that if the user enter both of the password correctly and then modify the first, the second becomes invalid (gets a red background-color).

So in the Form component I want to trigger a reevaluation of the second password Input, every time the value of the first password changes.

In the Form I have the value of the first password stored in a useReducer state, and I thought that passing it in the props of a component would automatically trigger a reevaluation, but that's not the case.

Password
[*****_____]

Re-enter Password
[*****_____]  // "valid" because it has the same value of the first password



...then the user modify the first password:

Password
[********__]

Re-enter Password
[*****_____]  // this component should be reevaluated and set itself to "invalid"

I pass the value of the first password in the props of the second component here:

<Input
    ...props...
    testingFunction={password => password && password === formState.password.value}
/>

I also tried to pass the value more explicitly by adding this property: dependencies={formState.password.value}, but it doesn't work either.

So what's wrong with this approach and what would be a good way to force a reevaluation of the second password component?

1 Answers

You can use useEffect to run your re-evaluation in your Input component.

E.g.

import React, { useEffect } from "react";

interface IInputProps extends HTMLInputElement {
  reevaluate?: string;
}

const Input: React.FC<IInputProps> = (props: IInputProps) => {
  useEffect(() => {
    console.log("Run your evaluation code here - This code block will be run whenever `reevaluate` prop is changed");
  }, [props.reevaluate])

  return (
    <input type="text" />
  );
};
Related