In my application, I need something like:
When a questions value is null then the checkbox should be shown as indeterminate, otherwise should be checked or not-checked.
But the problem is that when I update the questions, it shows me the error:
TypeError: Cannot set property 'indeterminate' of null
My questions object in state is like this:
questions: [{
id: 1,
title: 'First Question',
answers: [
{
id: 2,
title: 'Java',
value: ''
},
{
id: 3,
title: 'Python',
value: ''
},
{
id: 4,
title: '.NET',
value: true
}
]
}]
So it means that the third checkbox should be checked, and other two should be shown as indeterminate. See picture below:
So when I click on the first one, it should become unchecked,and after clicking it again, its value should be true and should become checked. And their value will never be ''
ever, except that it can be the first time.
Here's the question.jsx
setIndeterminate = (elm, value) => {
if (value !== '') {
elm.checked = value;
elm.indeterminate = false;
}
else {
elm.checked = false;
elm.indeterminate = true;
}
}
handleOnChange = ({ currentTarget: checkbox }) => {
var questions = [...this.state.questions];
questions.map(p => {
p.answers.map(a => {
if (a.id == checkbox.id) {
a.value = (a.value === '') ? false : !a.value;
return;
}
})
})
this.setState({
questions
})
}
render() {
const { questions } = this.state;
return (
{questions.map(question =>
{question.answers.map(answer =>
<input onChange={this.handleOnChange} ref={elm => this.setIndeterminate(elm, answer.value)} value={answer.value} className="form-check-input" type="checkbox" id={answer.id} name={answer.id} />
)}
)}
)
}
How is that possible of happening since as you can see I am already setting the value of intermediate to either true or false?
Aucun commentaire:
Enregistrer un commentaire