Rev 464 | Rev 466 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useState, useEffect } from "react";
const Option = (props) => {
// get props
const { question } = props;
// init States
const [input, setInput] = useState(question.answer);
/**
* Update question answer
* @param {*} answer
*/
const handleAnswerSimple = (value) => {
setInput(value);
question.answer = value;
}
/**
* Update question answer
* @param {*} option
*/
const handleAnswerMultiple = (option) => {
console.log(option);
question.answer.includes(option.slug_option) ?
question.answer = removeOptionMultiple(question.answer, option.slug_option) :
question.answer.push(option.slug_option);
option.checked = true;
console.log(option);
setInput(question.answer);
}
/**
* Delete existing option
* @param {*} arr
* @param {*} item
* @returns
*/
const removeOptionMultiple = (arr, item) => arr.splice(arr.indexOf(item), 1);
/**
* componentDidMount
*/
useEffect(() => {
setInput(question.answer);
}, [question]);
return (
<div>
{question.options.map((opt, key) => {
return (
<div className="checkbox"
key={key}>
{question.type == 'multiple' &&
<input
type="checkbox"
name={`${opt.slug_option}[]`}
value={opt.slug_option}
checked={opt.checked}
onChange={() => handleAnswerMultiple(opt)}
/>
}
{question.type != 'multiple' &&
<input
type="radio"
name={`${opt.slug_question}`}
value={opt.slug_option}
checked={input == opt.slug_option}
onChange={() => handleAnswerSimple(opt.slug_option)}
/>
}
<div
dangerouslySetInnerHTML={{ __html: opt.text }}
className="option"
/>
</div>
)
})}
</div>
)
}
export default Option;