1

I have react-select dropdown menu and hidden input which I pass to form when submiting... using useState hook I created variable which tracks changes to react-select dropdown menu. Hidden input has this variable as value also. I thought this would be enough. But when I submit the form, console. log shows me that value of input is empty despite that variable that was selected from dropdown menu is actually updated.

I mean variable that I have chosen console logs some value, but hidden input thinks that it is still empty.

Does it means I have to rerender manually page each time I change that variable so input gets it's new value using useEffect ? Which is bad solution for me, I don't like it, thought it would be done automatically.

Or instead of useState I must create and use variable via Redux ? Which I also don't like, use redux for such small thing fills overcomplicated.

Isn't there any nice elegant solution ? :)

import { useForm } from 'react-hook-form';

        const [someVar,setSomeVar]=useState('');
        
const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ mode: 'onBlur' });
  const handleFormSubmit = (data) => {
       console.error('success');
  };
  const handleErrors = (errors) => {
    console.error(errors);
    console.log(document.getElementsByName('hiddenInput')[0].value);
  };
  const options = {
    hiddenInput: {
      required: t('hiddenInput is required'),
    },
  };


        .......
    <form onSubmit={handleSubmit(handleFormSubmit, handleErrors)}>
         <Select
         options='...some options list'
         onChange={(value) => setSomeVar(value)}
        />
        <input
        name='hiddenInput'
        value={someVar} 
        {...register('hiddenInput', options.hiddenInput)}
        />
    <button>submit</button>
        </form>

UPDATED

3
  • Could you post the surrounding code, including the form and submit handler? Commented Oct 8, 2022 at 20:03
  • Also wherever you call validate and the validation function -- tbh probs just post the whole component Commented Oct 8, 2022 at 20:04
  • whole component is overcomplecated. I think this example is enough. I've edited my post. please have a look Commented Oct 8, 2022 at 20:08

1 Answer 1

1

Its because getElementsByName returns an array of elements.

You probably want

document.getElementsByName('hiddenInput')[0].value

I should add that really you should use a ref attached to the input and not access it via the base DOM API.

const hiddenRef = useRef(null)

// ...

cosnt handleSubmit =(e)=>{
    console.log(hiddenRef.current.value);

}

// ...

  <input
    name='hiddenInput'
    value={someVar} 
    ref={hiddenRef}
    />

However as you are using react-hook-form you need to be interacting with its state store so the library knows the value.

const {
    register,
    handleSubmit,
    formState: { errors },
    setValue
  } = useForm({ mode: 'onBlur' });

// ...
    <form onSubmit={handleSubmit(handleFormSubmit, handleErrors)}>
         <Select
         options='...some options list'
         onChange={(value) => setValue('hiddenInput', value)}
        />
        <input
        name='hiddenInput'
        {...register('hiddenInput', options.hiddenInput)}
        />
    <button>submit</button>
        </form>

You can remove const [someVar,setSomeVar]=useState('');

However, this hidden input is not really necessary as you mention in comments. You just need to bind the dropdown to react hook form.

// controller is imported from react hook form

<form onSubmit={handleSubmit(handleFormSubmit, handleErrors)}>
<Controller
 control={control} // THIS IS FROM useForm return
  name="yourDropdown"
  rules={{required: true}}
  render={({
    field: { onChange, value, name, ref }
  }) => (
       <Select
         options={options}
         inputRef={ref}
         value={options.find(c => c.value === value)}
         onChange={val => onChange(val.value)}
        />
  )}
/>
  
    <button>submit</button>
        </form>
Sign up to request clarification or add additional context in comments.

14 Comments

ok u are right, probably I have problems with validation then ? can I edit my post and show validation ?
Let me take a look
Edited. Right yes, I did feel something was off here. The hidden input is not really necessary. What you really need is to properly bind <Select>. Give me a bit more time to edit further :D
Yeh its a little annoying. Basically it helps you bind 3rd party libs to react hook form. See react-hook-form.com/api/usecontroller/controller. I would probaly break his out into a new component that you pass props down into (that new component would have the controller in it) so you dont end up doing it lots of times.
Have a look at stackoverflow.com/questions/66317381/…, there is a slightly more neat controller implementation there.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.