basically I'm doing a kind of questionnaire, where questions are set out and with buttons you can express your choice from "little interest" to "very important" (from "1" to "4" respectively)
the method I used is this, although it doesn't seem to be the nicest/most efficient method:
<div className="mt-4 d-grid gap-2 col-8 mx-auto">
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="1" onClick={e => handleAnswers(e, "value")}>Molto poco</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="2" onClick={e => handleAnswers(e, "value")}>Abbastanza</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="3" onClick={e => handleAnswers(e, "value")}>Importanti</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="4" onClick={e => handleAnswers(e, "value")}>Fondamentali</button>
</div>
This is the function being called:
const handleAnswers = (e) => {
e.preventDefault();
let questionResponse = e.target.value; //=====> This is where i get the answere value
let questionId = currentQuestionCounter;
setAnswers([...answers, { questionId, questionResponse }]);
nextQuestion();
}
Is there any way to achieve the same result but in a more beautiful/functional way?
CodePudding user response:
Use e.currrentTarget.value
const handleAnswers = (e) => {
e.preventDefault();
let questionResponse = e.currentTarget.value;
let questionId = currentQuestionCounter;
setAnswers([...answers, { questionId, questionResponse }]);
nextQuestion();
}
The HTML code can be less verbose
<div className="mt-4 d-grid gap-2 col-8 mx-auto">
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="1" onClick={handleAnswers}>Molto poco</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="2" onClick={handleAnswers}>Abbastanza</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="3" onClick={handleAnswers}>Importanti</button>
<button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value="4" onClick={handleAnswers}>Fondamentali</button>
</div>
CodePudding user response:
I think your method is the most simple one to understand. Even when u look at it some later time.
CodePudding user response:
So probably the correct answer is between @jonrsharpe's comment and @mariko's response
Basically I did this:
{
["Molto poco", "Abbastanza", "Importanti", "Fondamentali"].map((label, index) => {
return (
<Button className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value={index 1} onClick={handleAnswers}>{label}</Button>
)
})
}
And for the function i did this:
const handleAnswers = (e) => {
e.preventDefault();
let questionResponse = e.currentTarget.value;
let questionId = currentQuestionCounter;
setAnswers([...answers, { questionId, questionResponse }]);
nextQuestion();
}