Alexby
Alexby

Reputation: 33

How to use React Hook Form with RNPickerSelect in React Native?

I am trying to use RNPickerSelect (https://github.com/lawnstarter/react-native-picker-select) with react-hook-form in React Native. I've tried with Controller wrapper to use RNPickerSelect component. And it always invokes 'required' error. Could someone please point me to right direction? Here is my code.

const CategoryContentView = () => {
   const tempData = [];
   categories.forEach((data) => {
     tempData.push({ label: `${data.name}`, value: `${data.id}` });
   });
   return (
     <>
       <Controller
         as={
           <RNPickerSelect
           onValueChange={(value) => {
             setCategory(value);
           }}
           items={tempData}
         />}
         rules={{
         required: true,
       }}
         control={control}
         name="category"
         valueName="value"
         onChange={([value]) => value}
         error={!!get(errors, 'category')}
       />
       {errors.category && <ErrorView errors={['this is required']} />}
     </>
 };

Thank you in advance

Upvotes: 1

Views: 4109

Answers (1)

mSenad
mSenad

Reputation: 133

I'm probably late but here is the example:

<Controller
render={({onChange, ...props}) => {
    <RNPickerSelect
      {...props}
      onValueChange={(value) => {
        onChange(value);
      }}
      items={tempData}
    />
  }}
  rules={{
    required: true,
  }}
  control={control}
  name="category"
  valueName="value"
  error={!!get(errors, "category")}
/>;

So, render prop is actually a function that has a couple of parameters and onChange is one of them. This method should be called every time you want to update your value and that's why I called it inside a onValueChange as you can see it in the example.

Upvotes: 2

Related Questions