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
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:
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.
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