I have this code, where I have an object that represents a single choice question, I want to get the changes that are made inside it in the state of the app, so I can update my backend later
const EditableQuestion = ({handleChange,questionId,correctAnswer,points,text,ans1,ans2,ans3,ans4, ...otherProps}) => (
<div className='editable-question'>
<div className='question-text'>
<textarea onChange={handleChange} name="text" id="" cols="30" rows="5" defaultValue={text}></textarea>
</div>
<div className='question-answers'>
<div className='answer'><input type='radio' onChange={handleChange} name={questionId} defaultChecked={1 === correctAnswer}/><input type='text' defaultValue={ans1}/></div>
<div className='answer'><input type='radio' onChange={handleChange} name={questionId} defaultChecked={2 === correctAnswer}/><input type='text' defaultValue={ans2}/></div>
<div className='answer'><input type='radio' onChange={handleChange} name={questionId} defaultChecked={3 === correctAnswer}/><input type='text' defaultValue={ans3}/></div>
<div className='answer'><input type='radio' onChange={handleChange} name={questionId} defaultChecked={4 === correctAnswer}/><input type='text' defaultValue={ans4}/></div>
</div>
<div className='points'>
<input type='text' onChange={handleChange} defaultValue={points}/>
<span>points</span>
</div>
</div>
)
export default EditableQuestion;
The main app code looks like this:
class QuizEdit extends React.Component{
constructor(props){
super(props);
this.state = {
title : '',
time : null,
questionNr : 2,
questions : [
{
questionId : 1,
text : "This is a test question text",
ans1 : "Possible answer 1",
ans2 : "Possible answer 2",
ans3 : "Possible answer 3",
ans4 : "Possible answer 4",
correctAnswer : 1,
points: 5
},
{
questionId : 2,
text : "This is the second test question text",
ans1 : "Possible answer 1",
ans2 : "Possible answer 2",
ans3 : "Possible answer 3",
ans4 : "Possible answer 4",
correctAnswer : 2,
points: 10
}
]
}
}
handleChange = event => {
console.log("value");
}
render(){
const {questions,questionNr} = this.state;
return(
<div className='quiz-edit'>
<div className='quiz-question'>{
questions.map(({questionId,correctAnswer,points,text,ans1,ans2,ans3,ans4,...otherDraftProps}) => (
<EditableQuestion onChange={this.handleChange} key={questionId} questionId={questionId} text={text} ans1={ans1} ans2={ans2} ans3={ans3} ans4={ans4} correctAnswer={correctAnswer} points={points}{...otherDraftProps}/>
))
}
</div>
</div>
)
}
}
export default QuizEdit;
I have some dummy data in the state so I can test the code, when I type anything in the EditableQuestion component fields I expect the console.log from the handleChange function to get triggered. but it's not the case, nothing happens
handleChangebut you pass it anonChange. ChangeonChange={this.handleChange}tohandleChange={this.handleChange}