FormValidator not working in simple form

1 Answer 67 Views
Form
Daniela
Top achievements
Rank 1
Iron
Iron
Iron
Daniela asked on 22 Oct 2021, 09:05 AM

 

Hello,

 

Im using the validation form fields but for some reason my state is not being updated after I enter valid data, on form submission the inputs are all null even thought I had entered valid data. some help would be greatly appreciated. Part of the code is below

 

 

  

 

 const data = {
    manufacturer_id: parseInt(manufacturerId)||null,
    comp_model: compModel||null
    comp_type_id: parseInt(compTypeId)||null,
    comp_nickname: compNickname||null,
    comp_serial_no: compSerialNo||null,
    comp_pressure: parseFloat(compPressure)||null,
    comp_pressure_unit: compPressureUnit.id||null,
    comp_regulation: compRegulation.id||null,
    comp_cooling: compCooling.id||null,
    comp_year: compYear.text||null,
    comp_power_supply: compPowerSupply.id||null,
    comp_power_supply_unit: null,
    comp_motor_power: parseInt(compMotorPower)||null,
    comp_motor_power_unit: compMotorPowerUnit.id||null,
    comp_output: parseFloat(compOutput)||null,
    comp_output_unit: compOutputUnit.id||null,
    real_comp_data_id: idCreatedCompressor
  } 
 
  /**
  * Function to save Compressor Data.
  * Error message will save in the 'message' state.
  */
  const postCompressorSave = async (e=> {  
    debugger;
    const isEmpty = Object.values(data).every(x => x === null || x === '');
    if(isEmpty) {
      return;
    }
    if(idCreatedCompressor !== "") {
      postCompressorUpdate();  
      return;
    }
    const dataWithStatus = {...datadata_status_flow_id:status.IN_PROGRESS}
    try{
    const result = await authAxios.post(`/compressors`dataWithStatus)
      setIdCreatedCompressor(result.data)
      console.log(idCreatedCompressor);
    }catch(err){
      console.log("AXIOS ERROR"err.message);
    }
  }
    

 

 

constNicknameInput = (fieldRenderProps=> {

  
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
             <label for="nickname-name" className="text-info">Nickname</label>
             <Input type="text" name="nickname" placeholder=""
              style={{height: "30px"}}
              onChange={e=>setCompNickname(e.target.value)}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    };
    
    const SerialNoInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div>
              <label for="serial-no-name" className="text-info">Serial No</label>
              <Input type="text" name="serialNo" placeholder=""
              style={{height: "30px"}}
              onChange={e=>setCompSerialNo(e.target.value)}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    };
    
    const MotorPowerInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div>
            <label for="motor-power-name" className="text-info">Motor Power</label>
            <Input type="text" name="motor-power" placeholder="ex: 75"
               style={{height: "30px"}}
               onChange={e=>setCompMotorPower(e.target.value)}
               {...others}/> 
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
    const pressureUnitInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
            <label for="rated-pressure-name" className="text-info">Rated Pressure</label>
            <Input type="text" name="pressure" placeholder=""
            style={{height: "30px"}}
            onChange={e=>setCompPressure(e.target.value)}
            {...others}/>
            <label for="rated-pressure-unit" className="text-info">{compPressureUnit}</label> 
            {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
    const OutputInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
            <label for="output-name" className="text-info">Output</label>
            <Input type="text" name="motor-power" placeholder="ex: 75"
            style={{height: "30px"}}
            onChange={e=>setCompOutput(e.target.value)}
            {...others}/>
            <label for="output-unit" className="text-info">{compOutputUnit}</label> 
            {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
     
  
  return (
          <Form className="mt-3 mb-4 px-0" onSubmit={postCompressorSave}
          render={(formRenderProps=> (
            <FormElement
              style={{
                maxWidth: 650,
              }}
            >
              <fieldset className={"k-form-fieldset"}> 
                <div className="mb-3">
                  <Field
                    name={"nickname"}
                    component={NicknameInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <Field
                    name={"serialNo"}
                    component={SerialNoInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <label for="cooling-name" className="text-info">Cooling</label>
                  <DropDownList
                      value={compCooling}
                      textField="text"
                      dataItemKey="id" 
                      onChange={(e=> {
                        setCompCooling(e.target.value);
                      }}
                      data={compCoolings}
                    /> 
                </div>
                <div className="mb-3">
                  <label for="year-manufactured-name" className="text-info">Year Manufactured</label>
                  <DropDownList
                        value={compYear}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompYear(e.target.value);
                        }}
                        data={years}
                      />   
                </div>
                <div>
                  <label for="power-supply-name" className="text-info">Power Supply</label>
                  <DropDownList
                        value={compPowerSupply}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompPowerSupply(e.target.value);
                        }}
                        data={compPowerSupplies}
                      /> 
                </div>  
                <div className="mb-3">
                  <Field
                    name={"motorPower"}
                    component={MotorPowerInput} 
                    validator={inputValidator}
                  /> 
                </div>   
                <div className="mb-3">
                  <Field
                    name={"ratedPressure"}
                    component={pressureUnitInput} 
                    validator={inputValidator}
                  /> 
                </div>    
                <div className="mb-3">
                  <Field
                    name={"output"}
                    component={OutputInput} 
                    validator={inputValidator}
                  /> 
                </div>    
              </fieldset>
              <div className="k-form-buttons">
                <button type={"submit"} className="btn btn-outline-success btn-block mt-1" 
                  style={{height: "30px"fontSize: "16px"paddingTop: "4px"}}>
                  Save
                </button>
              </div>
            </FormElement>
          )}
        />
              
  )
}

1 Answer, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 22 Oct 2021, 11:39 AM

Hello, Daniela,

This is expected as the Form is attaching its own onChange and value in order to control and know the value of each Field. If the developers overwrite it, the Form will not know about the value change and submit the Field with the initial value.

Please remove the onChange and value props from the Field and their custom components. If you still need this event for other logic on the app, this can be done:

<Input type="text" name="pressure" placeholder=""
            style={{height: "30px"}}
            onChange={e=>{
            props.onChange(e) // call the Form onChange and then execute any custom logic
            setCompPressure(e.target.value)
            }}
            {...others}/>

 

Regards,
Stefan
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 22 Oct 2021, 12:17 PM

Hello,

 

Sorry for interrupting again, I made your change (I guess the props are the input props please let me know if this is correct) and it still is not working, also it is not even stopping in the on change when the field changes. Do you probaby know how to fix it so it goes through my onchange?

    const NicknameInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
             <label for="nickname-name" className="text-info">Nickname</label>
             <Input type="text" name="nickname" placeholder=""
              style={{height: "30px"}} 
              onChange={e=>{
                debugger;
                fieldRenderProps.onChange(e// call the Form onChange and then execute any custom logic
                setCompNickname(e.target.value)
                }}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    };
    
Stefan
Telerik team
commented on 22 Oct 2021, 12:29 PM

Hello, Daniela,

Indeed, this will not call it at this point because our onChange is in `others` which overwrites this one. Still, the value has to be updated correctly. I made an example with the same code and the Form is correctly updated and the value is there during onSubmit:

https://stackblitz.com/edit/react-j1xfxy?file=app/main.jsx

If the issue still occurs, please share an example reproducing it and I will be happy to take a look.

Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 22 Oct 2021, 12:40 PM

Hello again,

I have made the change but still it is not working, the tihnig is that I am implementing autosave on onchange of any field so I have one useeffect tha triggers my save method and the value of the state is null after I change something in the input. For ex: I enter valid data, that triggers my method correctly but the data is null. sorry for all the bothering.

 

import React, {useContextuseStateuseEffectfrom 'react'
import { FormFieldFormElement } from "@progress/kendo-react-form";
import { Input } from "@progress/kendo-react-inputs";
import { Error } from "@progress/kendo-react-labels";
import { UserContext } from '../../contexts/UserContextProvider'
import APIURL from '../../configs/APIConfig'
import axios from 'axios';
import { DropDownList } from "@progress/kendo-react-dropdowns";
/**
* Component to add new Compressor.
*/
const AddCompData = () => {
  const { authToken } = useContext(UserContext);
  const [manufacturerIdsetManufacturerId] = useState('')
  const [compModelsetCompModel] = useState(''
  const [compTypeIdsetCompTypeId] = useState('')
  const [compNicknamesetCompNickname] = useState('')
  const [compSerialNosetCompSerialNo] = useState('')
  const [compPressuresetCompPressure] = useState('')
  const [compPressureUnitsetCompPressureUnit] = useState('')
  const [compRegulationsetCompRegulation] = useState('')
  const [compCoolingsetCompCooling] = useState('')
  const [compCoolingssetCompCoolings] = useState([])
  const [compYearsetCompYear] = useState([])
  const [compPowerSupplysetCompPowerSupply] = useState('')
  const [compPowerSuppliessetCompPowerSupplies] = useState([])
  const [messagesetMessage] = useState('')
  const [idCreatedCompressorsetIdCreatedCompressor] = useState('')
  const [compPowerSupplyUnitsetCompPowerSupplyUnit] = useState([])
  const [compMotorPowersetCompMotorPower] = useState('')
  const [compMotorPowerUnitsetCompMotorPowerUnit] = useState([])
  const [compOutputsetCompOutput] = useState('')
  const [compOutputUnitsetCompOutputUnit] = useState([])
  
  const year = 2001;
  const years = Array.from(new Array(20),( valindex=> ({text: index + year,id: index}));
  /**
  * These keys must match the DB keys for status
  */
  const status = {
    PUBLISH: 1,
    IN_PROGRESS: 2,
    VERIFIED: 3,
    REJECTED: 4,
  }
  /**
  * Validator
  */
  const inputRegex = new RegExp(/^([a-zA-Z\d\.,%/\-_ ].*)/);
  const inputValidator = (value=>
        inputRegex.test(value) ? "" : "Please enter a valid value.";
  /**
  * Axios (NPM) is used to send the 'Auth Token' through headers
  */
  const authAxios = axios.create({
    baseURL: APIURL.url,
    headers: {
      authorization: `Bearer ${authToken}`
    }
  })
/**
  * Fetch compPowerSupplies from the API.
  * Store data to 'compPowerSupplies' state.
  */
 const fetchcompPowerSuppliess = async () => {
  try{
    const result = await authAxios.get(`/compressorpowersupplies`)
    const newresult = result.data.map(e => ({text:e.comp_power_supply_name,id:e.comp_power_supply_id })); 
    setCompPowerSupplies(newresult)
  }catch(err){
    console.log("AXIOS ERROR"err.message);
  }
}
/**
  * Fetch fetchCompCollings from the API.
  * Store data to 'fetchCompCollings' state.
  */
 const fetchCompCollings = async () => {
  try{
    const result = await authAxios.get(`/compressorcoolings`)
    const newresult = result.data.map(e => ({text:e.comp_cooling_name,id:e.comp_cooling_id })); 
    setCompCoolings(newresult)
  }catch(err){
    console.log("AXIOS ERROR"err.message);
  }
}
  useEffect(()=>{
    fetchCompCollings()
    fetchcompPowerSuppliess()
  }, [])
  useEffect(() => {
    postCompressorSave()
   }, [compNicknamecompSerialNocompCoolingcompYearcompPowerSupply
      compMotorPower,compPressurecompOutput]);
  /**
  * Gather data from States and Create an object.
  */
  const data = {
    manufacturer_id: parseInt(manufacturerId)||null,
    comp_model: compModel||null
    comp_type_id: parseInt(compTypeId)||null,
    comp_nickname: compNickname||null,
    comp_serial_no: compSerialNo||null,
    comp_pressure: parseFloat(compPressure)||null,
    comp_pressure_unit: compPressureUnit.id||null,
    comp_regulation: compRegulation.id||null,
    comp_cooling: compCooling.id||null,
    comp_year: compYear.text||null,
    comp_power_supply: compPowerSupply.id||null,
    comp_power_supply_unit: null,
    comp_motor_power: parseInt(compMotorPower)||null,
    comp_motor_power_unit: compMotorPowerUnit.id||null,
    comp_output: parseFloat(compOutput)||null,
    comp_output_unit: compOutputUnit.id||null,
    real_comp_data_id: idCreatedCompressor
  } 
 
  /**
  * Function to save Compressor Data.
  * Error message will save in the 'message' state.
  */
  const postCompressorSave = async (e=> {  
    debugger;
    const isEmpty = Object.values(data).every(x => x === null || x === '');
    if(isEmpty) {
      return;
    }
    if(idCreatedCompressor !== "") {
      postCompressorUpdate();  
      return;
    }
    const dataWithStatus = {...datadata_status_flow_id:status.IN_PROGRESS}
    try{
    const result = await authAxios.post(`/compressors`dataWithStatus)
      setIdCreatedCompressor(result.data)
      console.log(idCreatedCompressor);
    }catch(err){
      console.log("AXIOS ERROR"err.message);
    }
  }
    /**
  * Function to save Compressor Data.
  * Error message will save in the 'message' state.
  */
     const postCompressorUpdate = async () => {
      const dataWithStatus = {...datadata_status_flow_id:status.IN_PROGRESS}
      try{
        const result = await authAxios.post(`/compressors_update`dataWithStatus)
        setMessage(result.data)
        console.log(message);
      }catch(err){
        console.log("AXIOS ERROR"err.message);
      } 
    }
    const NicknameInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
             <label for="nickname-name" className="text-info">Nickname</label>
             <Input type="text" name="nickname" placeholder=""
              style={{height: "30px"}} 
              onChange={e=>{
                debugger;
                fieldRenderProps.onChange(e// call the Form onChange and then execute any custom logic
                setCompNickname(e.target.value)
                }}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    };
    
    const SerialNoInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div>
              <label for="serial-no-name" className="text-info">Serial No</label>
              <Input type="text" name="serialNo" placeholder=""
              style={{height: "30px"}}
              onChange={e=>setCompSerialNo(e.target.value)}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    };
    
    const MotorPowerInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div>
            <label for="motor-power-name" className="text-info">Motor Power</label>
            <Input type="text" name="motor-power" placeholder="ex: 75"
               style={{height: "30px"}}
               onChange={e=>setCompMotorPower(e.target.value)}
               {...others}/> 
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
    const pressureUnitInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
            <label for="rated-pressure-name" className="text-info">Rated Pressure</label>
            <Input type="text" name="pressure" placeholder=""
            style={{height: "30px"}}
            onChange={e=>setCompPressure(e.target.value)}
            {...others}/>
            <label for="rated-pressure-unit" className="text-info">{compPressureUnit}</label> 
            {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
    const OutputInput = (fieldRenderProps=> {
      const { validationMessagevisited, ...others } = fieldRenderProps;
      return (
        <div> 
            <label for="output-name" className="text-info">Output</label>
            <Input type="text" name="motor-power" placeholder="ex: 75"
            style={{height: "30px"}}
            onChange={e=>setCompOutput(e.target.value)}
            {...others}/>
            <label for="output-unit" className="text-info">{compOutputUnit}</label> 
            {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );
    }; 
     
  
  return (
          <Form className="mt-3 mb-4 px-0" onSubmit={postCompressorSave}
          render={(formRenderProps=> (
            <FormElement
              style={{
                maxWidth: 650,
              }}
            >
              <fieldset className={"k-form-fieldset"}> 
                <div className="mb-3">
                  <Field
                    name={"nickname"}
                    component={NicknameInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <Field
                    name={"serialNo"}
                    component={SerialNoInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <label for="cooling-name" className="text-info">Cooling</label>
                  <DropDownList
                      value={compCooling}
                      textField="text"
                      dataItemKey="id" 
                      onChange={(e=> {
                        setCompCooling(e.target.value);
                      }}
                      data={compCoolings}
                    /> 
                </div>
                <div className="mb-3">
                  <label for="year-manufactured-name" className="text-info">Year Manufactured</label>
                  <DropDownList
                        value={compYear}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompYear(e.target.value);
                        }}
                        data={years}
                      />   
                </div>
                <div>
                  <label for="power-supply-name" className="text-info">Power Supply</label>
                  <DropDownList
                        value={compPowerSupply}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompPowerSupply(e.target.value);
                        }}
                        data={compPowerSupplies}
                      /> 
                </div>  
                <div className="mb-3">
                  <Field
                    name={"motorPower"}
                    component={MotorPowerInput} 
                    validator={inputValidator}
                  /> 
                </div>   
                <div className="mb-3">
                  <Field
                    name={"ratedPressure"}
                    component={pressureUnitInput} 
                    validator={inputValidator}
                  /> 
                </div>    
                <div className="mb-3">
                  <Field
                    name={"output"}
                    component={OutputInput} 
                    validator={inputValidator}
                  /> 
                </div>    
              </fieldset>
              <div className="k-form-buttons">
                <button type={"submit"} className="btn btn-outline-success btn-block mt-1" 
                  style={{height: "30px"fontSize: "16px"paddingTop: "4px"}}>
                  Save
                </button>
              </div>
            </FormElement>
          )}
        />
              
  )
}
export default AddCompData

 

Stefan
Telerik team
commented on 25 Oct 2021, 05:22 AM

Hello, Daniela,

If the issue is that the value in the state `compNickname` is null, this is because the onChange is overwriten.  To ensure that this will not happened we can take it from the props:

  const NicknameInput = (fieldRenderProps) => {
   
         const { validationMessage, visited, onChange, ...others } = fieldRenderProps;
        <Input
          type="text"
          name="nickname"
          placeholder=""
          style={{ height: '30px' }}
          onChange={(e) => {
            debugger;
            onChange(e); // call the Form onChange and then execute any custom logic
            setCompNickname(e.target.value);
          }}
          {...others}
This will ensure that the onChange will not be set again from `others` .

Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 25 Oct 2021, 07:51 AM

Hello,

 

Thnanks that worked, I have added the onchange in this line

         const { validationMessage, visited, onChange, ...others } = fieldRenderProps;

and it is working now, but there is a new problem after that change I cannot freely type anything in the input, on type of a letter the input looses focus and I have to click it again to continue typing and again looses focus every time I type one letter, do you know why this might be happening?

 

Thanks

 

Regards,

Stefan
Telerik team
commented on 25 Oct 2021, 08:19 AM

Hello, Daniela,

I'm glad to hear that the initial issue is resolved.

As for the focus issue, this occurs as the validation is initialized as an inline function inside the AddCompData component. This causes React to re-mount it each time the state is updated which causes the component to lose focus as it is a new DOM element instance. 

This can be resolved by placing the validation function outside of the AddCompData component. This will not create a new instance every time and will allow freely typing the value.

Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 25 Oct 2021, 08:22 AM

Hello,

Thanks for your input, do you mean the inputValidator outside of the AddCompData? 

Do you probably have a quick example?

 

Thanks,

Stefan
Telerik team
commented on 25 Oct 2021, 08:33 AM

Hello, Daniela,

Yes, this is what I mean.

This can be seen in our demo where the EmailValidator is outside of the App component:

https://www.telerik.com/kendo-react-ui-develop/components/form/validation/
Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 25 Oct 2021, 08:52 AM

Hello,

 

Thanks for your response, I have tried that (taking the input validator out of the component) but still it is not working, also I cannot take out NicknameInput because the setCompNickName is in there and it is part of the component´s logic and I cannot take it out.

/**
* Validator
*/
const inputRegex = new RegExp(/^([a-zA-Z\d\.,%/\-_ ].*)/);
const inputValidator = (value=>
      inputRegex.test(value) ? "" : "Please enter a valid value.";
      
/**
* Component to add new Compressor.
*/
const AddCompData = () => {
  const [compNicknamesetCompNickname] = useState('')
 const NicknameInput = (fieldRenderProps=> {
      const { validationMessagevisitedonChange, ...others } = fieldRenderProps;
      return (
        <div> 
             <label htmlFor="nickname-name" className="text-info">Nickname</label>
             <Input type="text" name="nickname" placeholder=""
              style={{height: "30px"}} 
              onChange={e=>
                fieldRenderProps.onChange(e// call the Form onChange and then execute any custom logic
                setCompNickname(e.target.value)
                }}
              {...others}/>
              {visited && validationMessage && <Error>{validationMessage}</Error>}
        </div>
      );

    };

 return (
          <Form className="mt-3 mb-4 px-0" onSubmit={nextStepClick}
          render={(formRenderProps=> (
            <FormElement
              style={{
                maxWidth: 650,
              }}
            >
              <fieldset className={"k-form-fieldset"}> 
                <div className="mb-3">
                  <Field
                    name={"nickname"}
                    component={NicknameInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <Field
                    name={"serialNo"}
                    component={SerialNoInput} 
                    validator={inputValidator}
                  /> 
                </div> 
                <div className="mb-3">
                  <label htmlFor="cooling-name" className="text-info">Cooling</label>
                  <DropDownList
                      value={compCooling}
                      textField="text"
                      dataItemKey="id" 
                      onChange={(e=> {
                        setCompCooling(e.target.value);
                      }}
                      data={compCoolings}
                    /> 
                </div>
                <div className="mb-3">
                  <label htmlFor="year-manufactured-name" className="text-info">Year Manufactured</label>
                  <DropDownList
                        value={compYear}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompYear(e.target.value);
                        }}
                        data={years}
                      />   
                </div>
                <div>
                  <label htmlFor="power-supply-name" className="text-info">Power Supply</label>
                  <DropDownList
                        value={compPowerSupply}
                        textField="text"
                        dataItemKey="id" 
                        onChange={(e=> {
                          setCompPowerSupply(e.target.value);
                        }}
                        data={compPowerSupplies}
                      /> 
                </div>  
                <div className="mb-3">
                  <Field
                    name={"motorPower"}
                    component={MotorPowerInput} 
                    validator={inputValidator}
                  /> 
                </div>   
                <div className="mb-3">
                  <Field
                    name={"ratedPressure"}
                    component={pressureUnitInput} 
                    validator={inputValidator}
                  /> 
                </div>    
                <div className="mb-3">
                  <Field
                    name={"output"}
                    component={OutputInput} 
                    validator={inputValidator}
                  /> 
                </div>    
              </fieldset>
              <div className="k-form-buttons">
                <button type={"submit"} className="btn btn-outline-success btn-block mt-1" 
                  style={{height: "30px"fontSize: "16px"paddingTop: "4px"}}>
                  Next
                </button>
              </div>
            </FormElement>
          )}
        />
              
  )
}
export default AddCompData
Stefan
Telerik team
commented on 26 Oct 2021, 09:46 AM

Hello, Daniela,

This is caused by the same issue but for the NicknameInput component which is initialized inside the component and is being re-mounted. This can be resolved by moving the component outside of the main component. Then we can use React.Context to pass any extra props to that component, for example, to be able to update the main component state:

https://reactjs.org/docs/context.html

I made a runnable example based on this, where the Form and the state are synced and the user can type freely:

https://stackblitz.com/edit/react-kupycw?file=app/main.jsx

Daniela
Top achievements
Rank 1
Iron
Iron
Iron
commented on 27 Oct 2021, 08:53 AM

That worked, thank you so much ! 
Tags
Form
Asked by
Daniela
Top achievements
Rank 1
Iron
Iron
Iron
Answers by
Stefan
Telerik team
Share this question
or