skip to Main Content

I have a Api call which get a object with question Id and response Id given by the user. When I revisit the questions, I want to see the previously given answers checked in the radio button.

I can get the relevent responce id but how to make the radio button checked?

import React from "react";
import "./radioopions.css";
const RadioOptions = (props) => {
  const result = props.response;
  console.log("result 1:", result);

  const QID = props?.questionId;
  console.log("result 2:", QID);

  const getCheckedAnswer = () =>{
    {
      result?.map((res) => {
        if (QID === res?.questionId) {
          const answer = res?.response;
          console.log("res",res?.response)
          return answer;
          
        }
      });
    }
   
  }

  
  return (
    <div>
      <div className="radio-container">
        <div className="radio-options">
          {props.options?.map((ans, i) => {
            return (
              <div key={ans.optionID}>
                <div className="answer-options">
                  <input
                    type="radio"
                    className="ans-op-overlay-resolve"
                    value={3}
                    checked={
                      props.selectedAnswer === i || getCheckedAnswer()
                      //|| props.previousAnswer === res?.response
                    }
                    onChange={() => props.handleAnswerOPtion(i)}
                  />
                  <label htmlFor={`option-${i}`}>{ans.option}</label>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
export default RadioOptions;

2

Answers


  1. In order to automatically check the radio button which corresponds to the response of the user for the current question, I suggest you do use the following code:

    import React from "react";
    import "./radioopions.css";
    const RadioOptions = (props) => {
      const result = props.response;
      console.log("result 1:", result);
    
      const QID = props?.questionId;
      console.log("result 2:", QID);
    
      const getCheckedAnswer = () =>{
         return result?.find((res) => {
            return (QID === res?.questionId) 
          }); 
      }
    
      // This function will return the response id for the current question        id
    
      
      return (
        <div>
          <div className="radio-container">
            <div className="radio-options">
              {props.options?.map((ans, i) => {
                return (
                  <div key={ans.optionID}>
                    <div className="answer-options">
                      <input
                        type="radio"
                        className="ans-op-overlay-resolve"
                        value={3}
                        checked={
                          getCheckedAnswer()?.responseId === ans.optionId
                        }
                        onChange={() => props.handleAnswerOPtion(i)}
                      />
                      <label htmlFor={`option-${i}`}>{ans.option}</label>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      );
    };
    export default RadioOptio

    Feel free to make some changes to the above code, but the main idea is that you want to find the specific object inside of your response which belongs to the current question and it will give you the responseId that you require.

    After being able to retrieve that value, you can set the checked property to true in your radio buttons, only for the relevant option which matches the response that the user has provided for the current question.

    Login or Signup to reply.
  2. Change response value in apiResponse variable inside useEffect to set initial value for radio to be either 1, 2, or 3 => this is controlled component for radio button

    import { useState, useEffect } from "react";
    
    const questions = [
      {
        id: 1,
        text: "favorite color?",
        options: [
          { optionID: 1, option: "Red" },
          { optionID: 2, option: "Green" },
          { optionID: 3, option: "Blue" }
        ]
      },
      {
        id: 2,
        text: "favorite food?",
        options: [
          { optionID: 1, option: "Pizza" },
          { optionID: 2, option: "Burger" },
          { optionID: 3, option: "Salad" }
        ]
      }
    ];
    
    const RadioOptions = (props) => {
      const { response, questionId, options, handleAnswerOption } = props;
    
      const getCheckedAnswer = (optionID) => {
        const responseObj = response.find((res) => res.questionId === questionId);
        return responseObj ? responseObj.response === optionID : false;
      };
    
      const handleOnChange = (e) => {
        const answerId = parseInt(e.target.value);
        handleAnswerOption(questionId, answerId);
      };
    
      return (
        <div>
          <div className="radio-container">
            <div className="radio-options">
              {options?.map((ans, i) => {
                return (
                  <div key={ans.optionID}>
                    <div className="answer-options">
                      <input
                        type="radio"
                        id={`option-${i}`}
                        name={`question-${questionId}`}
                        value={ans.optionID}
                        checked={getCheckedAnswer(ans.optionID)}
                        onChange={handleOnChange}
                      />
                      <label>{ans.option}</label>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      );
    };
    
    const App = () => {
      const [response, setResponse] = useState([]);
    
      useEffect(() => {
        // Simulate API response data
        const apiResponse = [
          { questionId: 1, response: 1 },
          { questionId: 2, response: 2 }
        ];
        setResponse(apiResponse);
      }, []);
    
      const handleAnswerOption = (questionId, answerId) => {
        const newResponse = [...response];
        const responseIndex = newResponse.findIndex(
          (res) => res.questionId === questionId
        );
        if (responseIndex !== -1) {
          newResponse[responseIndex].response = answerId;
        } else {
          newResponse.push({ questionId, response: answerId });
        }
        setResponse(newResponse);
      };
    
      return (
        <div>
          {questions.map((q, i) => (
            <div key={q.id}>
              <p>{q.text}</p>
              <RadioOptions
                response={response}
                questionId={q.id}
                options={q.options}
                handleAnswerOption={handleAnswerOption}
              />
            </div>
          ))}
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search