Search code examples
javascriptreactjsantd

How to stop cursor jumps to the end?


I'm using Antd Input library, whenever I type in the start or in the middle of the word my cursor jumps to the end.

const handleOpenAnswer =( key, value )=>{
    handleFieldChange({
        settings: {
            ...settings,
            [key]: value
        }
    })
}
    
return (        
    <Input
        required
        size='default'
        placeholder='Label for Diference Open Answer Question'
        value='value'
        onChange={({ target: { value } }) => {
            handleOpenAnswer('differenceOpenAnswerLabel', value)
        }}
/>

Solution

  • The reason why your cursor always jumps to the end is because your parent component gets a new state and therefore re-renders its child components. So after every change you get a very new Input component. So you could either handle the value change within the component itself and then try to pass the changed value up to the parent component after the change OR (and I would really recommend that) you use something like React Hook Form or Formik to handle your forms. Dealing with forms on your own can be (especially for complex and nested forms) very hard and ends in render issues like you face now.

    Example in React-Hook-Form:

    import { FormProvider, useFormContext } = 'react-hook-form';
    
    const Form = () => {
      const methods = useForm();
      const { getValues } = methods;
      
      const onSubmit = async () => {
        // whatever happens on submit
        console.log(getValues()); // will print your collected values without the pain
      }
      
      return (
        <FormProvider {...methods}>
            <form onSubmit={(e) => handleSubmit(onSubmit)(e)>
               {/* any components that you want */}
            </form>
        </FormProvider>
      );
    }
    
    const YourChildComponent = () => {
      const { register } = useFormContext();
      
      return (
        <Input
            {...register(`settings[${yourSettingsField}]`)}
            size='default'
            placeholder='Label for Diference Open Answer Question'
        />
      )
    }