简体   繁体   中英

Getting values from radio buttons in reach-hook-form

I am learning to code in React and Next.js and when it comes to submitting data in forms is really easy with react-hook-forms, but when it comes to radio buttons I am struggling a bit. I have a step in my app that I need to select one option between 3, and I am using radio buttons to do this.

The code I am using here, returns paymentMethod: PayPal, no matter which option I select from all the radio buttons, I always get that.

/** @format */

import React, { useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import Cookies from 'js-cookie';
import { Store } from '../utils/Store';
import Layout from '../components/Layout';
import Main from '../components/ui/Main/Main';
import HeadlineThree from '../components/ui/Type/HeadlineThree/HeadlineThree';
import { Controller, useForm } from 'react-hook-form';
import Section from '../components/ui/Section/Section';
import Button from '../components/ui/Button/Button';

export default function Payment() {
  // iniciamos el formulario
  const {
    handleSubmit,
    control,
    setValue,
    getValues,
    formState: { errors },
  } = useForm();

  // levantamos el router para redirigir
  const router = useRouter();

  // useState de paymentMethods
  const [paymentMethod, setPaymentMethod] = useState('');

  // alcanzamos el Store
  const { state, dispatch } = useContext(Store);

  // pediremos los states
  const {
    cart: { shippingAddress },
  } = state;

  // comprobaremos si tiene address y si la tiene, el método de pago
  useEffect(() => {
    if (!shippingAddress.address) {
      router.push('/shipping');
    } else {
      setPaymentMethod(Cookies.get('paymentMethod') || '');
    }
  }, []);
  // handler del formulario
  const submitHandler = data => {
    console.log(data);
    if (!paymentMethod) {
      console.log(data);
    } else {
      console.log('ahora no');
      // dispatch({ type: 'SAVE_PAYMENT_METHOD', payload: paymentMethod });
      // Cookies.set('paymentMethod', paymentMethod);
      // router.push('/placeorder');
    }
  };

  return (
    <Layout title='Payment Method'>
      <Main css='padding--32'>
        <form
          onSubmit={handleSubmit(submitHandler)}
          className='display--grid gap--8'
        >
          <HeadlineThree>Payment Methods</HeadlineThree>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='PayPal'
            render={({ field }) => (
              <label>
                <input name='paymentMethod' type='radio' {...field} />
                <span>PayPal</span>
              </label>
            )}
          ></Controller>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='Stripeaaa'
            render={({ field }) => (
              <label>
                <input
                  defaultChecked='true'
                  name='paymentMethod'
                  type='radio'
                  {...field}
                />
                <span>Stripe</span>
              </label>
            )}
          ></Controller>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='Cash'
            render={({ field }) => (
              <label>
                <input
                  name='paymentMethod'
                  type='radio'
                  value='Cash'
                  {...field}
                />
                <span>Cash</span>
              </label>
            )}
          ></Controller>
          <Section>
            <Button type='submit' kind='action'>
              Continue
            </Button>{' '}
            <Button onClick={() => router.push('/shipping')}>Back</Button>
          </Section>
        </form>
      </Main>
    </Layout>
  );
}

When I execute this, only receive an: Object {paymentMethod: "PayPal"} and I suspect it is because it's the first on the group. Maybe I am missing something in order to get the selected value, not the first one one of the group.

You juste have to do the following to register input type radio. Controller ins't needed in your case:

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

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <input type="radio" {...register('paymentMethod')} value="PayPal" />
      <input type="radio" {...register('paymentMethod')} value="Stripeaaa" />
      <input type="radio" {...register('paymentMethod')} value="Cash" />

      <button>Submit</button>
    </form>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM