Как получать значения только отображаемых input?

Столкнулась с такой проблемой: У меня есть форма, которая содержит вложенный список (тип товаров), который в свою очередь инициирует появление блока параметров. Для каждого типа товара определенные параметры пример с типом Book

Параметров может быть различное колличество

пример с типом Furniture

Вложенный список и блок с параметрами генерируются из массива объектов. Каждый объект описывает один тип продукта и необходимые параметры. Вот в таком формате:

{
            typeName: "Book",
            text: "Please provide dimension in KG",
            params: [
                {
                    paramName: "weight",
                    measureUnit: "KG",
                    validation: "number"
                },
            ]
        },

Суть проблемы: при отправки формы в объект с данными попадают данные всех параметров всех типов вне зависимости от того, какой тип выбран при отправлении. Каким способом можно избежать такого поведения?

Код самой формы:

import TypeSwitcher from "../typeSwitcher/TypeSwitcher";
import classes from "./NewProduct.module.sass";
import { useNavigate } from "react-router-dom";
import { useForm } from 'react-hook-form';



function NewProduct(props) {

    const { register, handleSubmit } = useForm({
    });

    const navigate = useNavigate();



    function SubmitHandler(data) {
        console.log(data);
        navigate('/');

    }


   return <form id="product_form" onSubmit={handleSubmit(SubmitHandler)} >
        <div className={classes.param_block}>
            <label htmlFor="title">SKU</label>
            <input name="sku" type="text" required id="sku" {...register("sku")} />
        </div>
        <div className={classes.param_block}>
            <label htmlFor="title">Name</label>
            <input name="name" type="text" required id="name" {...register("name")} />
        </div>
        <div className={classes.param_block}>
            <label htmlFor="title">Price</label>
            <input name="price" type="text" required id="price" {...register("price")} />
        </div>

//props.types - массив с объектами, описывающими типы
        <TypeSwitcher 
        register={register}
        types={props.types} />
    </form>
}

export default NewProduct;

Код TypeSwitcher:

import classes from './TypeSwitcher.module.sass';
import { useState } from 'react';

function TypeSwitcher (props) {
    const dataTypes = props.types;
    let typeNames = GetTypes();

    const [productType, setProductType] = useState("");


    function GetTypes () {
        let names = [];
        for(let typeItem of dataTypes) {
            names.push(typeItem.typeName); 
        }
        return names;
    }

    function CreateSwitcher(types) {
        return types.map((type)=>
            <option value={type} key={type}>{type}</option>
    )
    }

    function SwitchHandler(event) {
       setProductType(event.target.value);

        }
        
    

    function CreateTypeBlok() {
        for(let type of dataTypes) {
            
            let paramBlock=[];

            if (type.typeName === productType) {
               let text = <p>{type.text}</p>
                
                
                for(let param of type.params) {
                paramBlock.push( <CreateOption 
                   text={param.paramName+' ('+param.measureUnit+')'}
                   name={param.paramName} key={param.paramName} />)
                }   
                    
                return <>
                {text}
                {paramBlock}
                </>    


            }
        }
    }

   
    function CreateOption (propsOption) 
    {
        return <div className={classes.option_block}>
            <label htmlFor="title">{propsOption.text}</label>
            <input type="text" required id={propsOption.name} {...props.register(propsOption.name)} />
        </div>
    }


    return <>
    
        <div className={classes.switcher_block}>
            <label htmlFor="title">Type Switcher</label>
            <select  
                name="option" 
                id="productType" 
                {...props.register("type")}
                defaultValue={"DEFAULT"}
                onChange={SwitchHandler} >
                <option disabled value="DEFAULT">TypeSwitcher</option>
                {CreateSwitcher (typeNames)}
            </select> 
        </div>  
        {CreateTypeBlok()} 
               
              
        
        
        </>

}

export default TypeSwitcher;

Заранее спасибо за помощь!


Ответы (0 шт):