skip to Main Content

I have several filters and they are used by two parents. Both parents have apply button and I want when it is clicked validation function inside each filter to be called. How I can do that?

function DateFilter() {
  const [isError, setError] = useState(false);
  function validation() {
    // if not valid show error message and apply button disabled
    setError(true);
  }

  return ...
}
<DesktopDialog onApply={sendBackend}> <-- apply button is there
  <DateFilter onChange={setForm}>
</DesktopDialog>

and

<MobileFilterModal onApply={sendBackend}> <-- apply button is there
  <DateFilter onChange={(v) => setForm('date', v)}>
  ...other filters
</MobileFilterModal>

I heard we can use useImperativeHandle but are there alternative options I can use?

2

Answers


  1. You have to rethink your component structure. What you’re trying to achieve is anti-pattern in React as the data can flow only one way.

    The validation should happen in your parent component and DateFilter should probably just receive the result of it. You can extract this common functionality into a hook for example.

    There might be multiple ways to do this, it all really depends on your application and its architecture.

    Login or Signup to reply.
  2. If you told about a lot of parents. Right way will be lifted state up. For instance you can use context api

    A usage example similar to your case:
    https://dmitripavlutin.com/react-context-and-usecontext/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search