This is all new to me and I'm still learning. I'm trying to create a form quiz, including an input title, an input question, and a few input answers (with a checkbox).
A button '+add answer' is created to be able to add new inputs 'answer' in the quiz.
I created an array of objects and now I need to be able to push into the array the new inputs when I click on the button '+add answer'. I know I have to use the .push() method, but the typescript makes it harder for me to know how to do that.
Here is the full code:
function QuizForm() {
const [inputTitle, setInputTitle] = useState<string>('');
const [inputQuestion, setInputQuestion] = useState<string>('');
const [answers, setAnswers] = useState<{
correct: boolean,
label: string,
value: string,
id: number
}[]>([
{
correct: false,
label: "Answer 1 ...",
value: "",
id: 0
},
{
correct: false,
label: "Answer 2 ...",
value: "",
id: 1
}
]);
return (
<div className="container-fluid w-75">
<h2 className="row my-3 justify-content-center title1">Quiz</h2>
<div>
<div className="row justify-content-center">
<Form.Control className="formbg form3" type="title" name="title"
placeholder={'Quiz title ...'}
onChange={(event => setInputTitle(event.target.value))}/>
</div>
<div className="row my-2 justify-content-center">
<Form.Control className="formbg form3" type="text" name="question" placeholder={'Question ...'}
onChange={(event => setInputQuestion(event.target.value))}/>
</div>
{
answers.map((item) => {
return (
<>
<div className="row mt-4 justify-content-center">
<Form.Control className="formbg form3" type="text" name="text" placeholder={item.label}/>
</div>
<div className="row">
<input type="checkbox" id="link1"/>
<label htmlFor="link1" className="my-2">Good answer</label>
</div>
</>
)
})
}
<div className="my-4 line2"/>
</div>
<div className="row">
<Button
className="addbutton border-0">+ add answer
</Button>
</div>
<div className="row my-5 justify-content-center">
<Button className="registerbutton" block size="lg" type="submit"
onClick={() => console.log({
inputTitle,
inputQuestion,
})}>Save</Button>
</div>
</div>
)
}
export default QuizForm;
Thanks so much!
<Button onClick={() => setAnswers([...answers, newAnswer])} className="addbutton border-0">+ add answer </Button>should do the job. Read more about useState hook and destructuring