'How to know deep inside component hierarchy we have a special component, efficiently?

I'm creating a form builder using React.

The point is, everything is dynamic.

A form can have fields, or field groups. Each field group can have many fields. Each field can have it's own controls, hints, valdiations, etc.

This means that a form is a component hierarchy. A tree of components.

Now I want to know if in this tree, any Upload field exist at all.

Because if there is no Upload field, then I submit the form using application/json content type. Otherwise I would submit the form using application/form-data content type.

I know I can traverse the entire JSON of component props. But that seems very inefficient.

Is there a way to traverse React's component tree in an efficient way?



Solution 1:[1]

You can do so by using contextApi or with its hook for React Version > 16.8 the useContext.
Read more in React official docs

My suggestion is to use formik npm package to build your form correctly and easily, formik using context for managing the state behind the scene.
I recommend it for regular use of forms, not heavy form with many fields (~25-30 max) like in enterprises.
You can read about formik more here: https://formik.org/docs/api/formik
There is another alternative for formik which is also popular in react using forms:
react form hook: https://react-hook-form.com/
I didn't use it yet but as I know it has some pros/cons over formik.

Solution 2:[2]

Easiest way is vanilla JS.

const FORM_SELECTOR = '#some-form-id';
const UPLOAD_SELECTOR = '.some-upload-class';

const form = document.querySelector(FORM_SELECTOR)
if(form.querySelectorAll(UPLOAD_SELECTOR).length) {
  // upload exists
} else {
  // upload does not exist
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LironShirazi
Solution 2 Kristiyan Tsvetanov