The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component:

import FormControl from "@material-ui/core/FormControl";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Grid from "@material-ui/core/Grid";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup/RadioGroup";
import Typography from "@material-ui/core/Typography";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import SyntaxHighlighter from "react-syntax-highlighter";
import { dark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { Dispatch } from "redux";
import { incrementQuestion, IQuestion, questionRequest } from "../../actions/index";
import ContentQuiz from "../../components/ContentQuiz";
import history from "../../history/history";

interface IProps {
  currentQuestionNumber: number;
  loadingData: boolean;
  questions: IQuestion[];
  questionRequest: () => void;
  incrementQuestion: (arg: number) => void;
  numberOfQuestions: number;
}

const Quiz = (props: IProps) => {
  const { currentQuestionNumber,
    loadingData,
    questions,
    questionRequest,
    incrementQuestion,
    numberOfQuestions } = props;

  const [answerOption, setAnswerOption] = useState(1);

  useEffect(() => {
    questionRequest();
  }, [questionRequest]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAnswerOption(Number((event.target as HTMLInputElement).value));
  };
  const handleNextQuiz = () => {
    if (currentQuestionNumber === numberOfQuestions - 1) {
      history.push("/homepage");
    } else {
      incrementQuestion(answerOption);
      history.push("/contentQuiz");
    }
  };

  const currentQuestion = questions[currentQuestionNumber];
  return (
    <div>
      {loadingData ? ("Loading ...") : (
        < ContentQuiz
          questionNumber={currentQuestionNumber + 1}
          handleClick={handleNextQuiz} >
          <div>
            <Typography variant="h3" gutterBottom> What's the output of </Typography>
            <>
              <SyntaxHighlighter language="javascript" style={dark} >
                {currentQuestion.description.replace(";", "\n")}
              </SyntaxHighlighter >
                <Grid container direction="column" alignItems="baseline">
                  <Grid>
                    <FormControl component="fieldset">
                      <RadioGroup
                        name="option"
                        value={answerOption}
                        onChange={handleChange}>
                        {currentQuestion.options.map((option: string, index: number) => (
                          <FormControlLabel
                            key={index}
                            control={<Radio color="secondary" />}
                            label={option}
                            value={index + 1}
                            labelPlacement="end"
                          />))
                        }
                      </RadioGroup>
                    </FormControl>
                  </Grid>
                </Grid>
            </>
          </div >
        </ContentQuiz >
      )}
    </div>
  );
};

const mapStateToProps = (state: any) => {
  const { currentQuestionNumber, loadingData, questions, numberOfQuestions } = state.quiz;

  return {
    currentQuestionNumber,
    loadingData,
    questions,
    numberOfQuestions
  };
};

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    incrementQuestion: (answer: any) => dispatch<any>(incrementQuestion(answer)),
    questionRequest: () => dispatch<any>(questionRequest())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Quiz);

Nevertheless, the code above allows for checking different options, even though the standard functionality of Radio buttons dictates that only one option can be selected at a time. Seeing a similar query on Stack Overflow, I attempted to modify my code based on the answer provided. However, the handleChange function is not being triggered in my case, and I'm uncertain as to why.

Answer №1

After reviewing the information from the provided link, it seems that you can implement the following steps:

  1. Include the functional component below:

    const FormControlLabelWrapper = props => {
    const { index, option, ...labelProps } = props;
          return (
            <FormControlLabel
              key={index}
              control={<Radio color="secondary" />}
              label={option}
              value={index + 1}
              labelPlacement="end"
              {...labelProps}
            />
          );
        };
    
  2. Modify the currentQuestion.options.map to the code snippet provided below

    {currentQuestion.options.map((option: string, index: number) => 
    (<FormControlLabelWrapper
      option={option}
      index={index}
     />))}
    

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

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

The function $.getJSON() seems to be non-responsive

I've been struggling to solve this issue for quite some time now. The users.json file that I am using can be found in the "JSON" folder alongside the other files. The alert("Before") is functioning properly, but I'm facing difficulty with getting ...

Guide on programmatically closing a Bootstrap 5 offcanvas in Next Js

I have integrated Bootstrap 5 into my NextJs app by installing it using the command: npm install bootstrap and then importing the necessary files into my project via _app.js as shown below: import 'bootstrap/dist/css/bootstrap.css' ... useEffec ...

Tips on Modifying JSON Objects with JavaScript

In the code I'm working with, there's a generated line that creates an animated sidebar using a div. The width of this sidebar is controlled by the 'v' parameter, currently set to 85. <div id="sidebar" class="inner-element uib_w_5 ...

PHP Bootstrap Confirmation Dialog Tutorial

Is there a way to implement a delete confirmation dialog? When 'yes' is clicked, the message should be deleted, and when 'no' is clicked, the delete operation should be canceled. At present, this is how it looks in my view: <a href ...

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...

Get rid of the TypeScript error in the specified function

I am currently working on implementing a "Clear" button for a select element that will reset the value to its default state. Here is a snippet of my code: const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => { onChange( ...

Blazor combines the power of both C# and JavaScript by allowing them to be executed in a single

There is a button that triggers a JavaScript function: <button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button> And there is another button that executes C# code and toggles ic ...

Delaying Text Appearance in React-Native Component

I am currently working on a component that fetches data from an API and displays it on the screen. I would like to find out how I can delay showing the text on the screen until the API call is complete. For example: Your Balance is ____ after the networ ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

What is the process for switching directories and renaming a file when uploading in nodeJs?

I am currently using multer and fs to handle the upload of an image file. How can I modify the directory where uploaded files are stored? Currently, all files are saved in my "routes" folder instead of the "uploads" folder created by multer. Additionally, ...

Having trouble with the video player not working correctly in Safari when using the video-react package for videos?

Whenever we attempt to set the player start time to any seconds other than 00:00:00, the player actually starts at 00:00:00 and then seeks to the correct seconds after playing for a second or less. This issue is specific to Safari browser and we are curren ...

Utilizing the same NextJs page layout, showcase varying sets of information

As I work on my Next.js app, I am faced with the challenge of creating two pages that share the same design but present different data. What is the most effective way to achieve this while ensuring that each page has a unique URL path? ...

Encountering issues with resolving 'devextreme/animation/frame' when integrating devextreme with a react application

I'm running into an issue while trying to implement the devextreme datagrid table in React. Upon importing it, I encounter the following error: ./node_modules/devextreme-react/core/templates-renderer.js Module not found: Can't resolve 'devex ...

Enhancing User Interfaces with React and CSS Styling

I need to incorporate two unique React components on my webpage: Component1 and Component2. Code for Page1: <Component1/> <Component2/> While the individual components will have their own CSS files for styling, I also have a page1.css file f ...

Tips for designing scrollable overlay content:

I am currently in the process of building a page inspired by the design of Hello Monday. Right now, I have added static content before implementing the parallax effect and auto-scroll. Here is my progress so far: Check out the Sandbox Link One challenge ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

How to achieve precise alignment with Material-UI Box components

Could someone assist me in understanding why the alignment between Typography and IconButton is not working properly in my particular scenario? Why is the IconButton positioned lower than the Typography? For reference, here is an example: https://codesand ...

Is my front-end JavaScript fetch request mistakenly being sent as a GET instead of a POST?

On clicking the submit button, a fetch request is triggered. Strangely, in the developer tools, it shows up as a GET request. I tested the request using Insomnia and it returned the handlebars site to me without any of my console logs appearing on either ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...