Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where users need to select one option out of three using radio buttons.

The issue I'm facing is that no matter which radio button I choose, the code always returns paymentMethod: PayPal. It seems like I'm not capturing the selected value correctly from the radio buttons group within my form.

/** @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() {
  const {
    handleSubmit,
    control,
    setValue,
    getValues,
    formState: { errors },
  } = useForm();

  const router = useRouter();

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

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

  const {
    cart: { shippingAddress },
  } = state;

  useEffect(() => {
    if (!shippingAddress.address) {
      router.push('/shipping');
    } else {
      setPaymentMethod(Cookies.get('paymentMethod') || '');
    }
  }, []);

  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>
  );
}

Upon executing this code snippet, I consistently receive an Object {paymentMethod: "PayPal"}, leading me to believe that the first radio button in the group is always being selected by default. I suspect there may be something missing in my implementation to properly capture the user-selected value instead of defaulting to the first option every time.

Answer №1

To register input type radio, you simply need to follow these steps without the use of a controller:

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

Ways to resolve the array to string conversion issue in PHP

In my PHP project, I am dealing with a dynamic array and trying to store the array result in a variable. However, I encountered an error: array to string conversion while coding. <?php require_once('ag.php'); class H { var $Voltage; ...

Using Angular NgRx - triggering an action from an effect once certain actions yield a result

I'm encountering difficulties in dispatching actions that require results from five other actions (all listed in my effect). Could someone lend a hand? Essentially, I need to trigger an action within the effect only after these five actions have retu ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

How can I retrieve a text file using an API in a Next.js application?

Is there a way to download a text file using an API in Next.js? The console.log(ninjas) function is already displaying the correct information. I have tested the API with Postman and it works perfectly. When I use GET in Postman, the same information is ...

Automatically load content using AJAX when scrolling within a HTML5 segment

Recently, I've been developing a website that dynamically loads new content from a MySQL database as the user scrolls. However, I've encountered an issue where the new content is loaded even with minimal scrolling, rather than only when reaching ...

Error in REACT Plotly: createPlotlyComponent function cannot be found

After upgrading to the most recent version of plotly, the example provided no longer works as expected. In the plotly-react readme, there is a reference to this specific codepen (found in the Loading from a tag section): https://codepen.io/rsreusser/pen/q ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Looping through a JSON array

Currently, I am working with asp.net in Visual Studio and using jQuery to call a web method. In asp.net, I am generating a dynamic datatable and then returning it by using JsonConvert.SerializeObject(dt). $.ajax({ type: 'POST', url: &apo ...

Passing a particular object from an array of objects as props in React Native

Suppose you have a static array consisting of 4 objects and the goal is to pass specific data items from the third object in this array. How can this task be accomplished? Let's consider an example: const ENTRIES = [ { name: "John" color: "#fffff" f ...

Using JavaScript within HTML documents

Need help with inserting JavaScript code from Google: <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362706866260-0'); }); </script> into existing JavaScript / HTML code: va ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Having difficulty retrieving an item from a knockout observable array

When fetching data from a web API and pushing it into an observable array, I wanted to make the items in the array observable as well. Unfortunately, I found that I couldn't access the object if I made it observable. function UpdateViewModel() { ...

React Link updates the URL without re-rendering the view

I'm encountering an issue with the <Link to=""> element in React. When I click on it, the URL changes but the view remains the same. However, upon refreshing the page, the correct component is displayed indicating that the router is functioning ...

Switching between tabs in a Material UI React Tab component can be achieved by changing the

Currently working on a React project that includes a tab component. The project has Tab 1 and Tab 2. When the user clicks on the content of Tab 1, my goal is to switch the active tab from Tab 1 to Tab 2. For example: I have two tabs, Tab1 and Tab2. Tab1 ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...