Replacing the newly checked radio button with the existing checked radio button without affecting the array size in on change in react
let questions;
class MatrixBoard extends React.Component {
constructor(props) {
super(props);
this.state = {
buttonDisabled: true,
questions: [],
};
this.submitHandler = this.submitHandler.bind(this);
this.changeRadioHandler = this.changeRadioHandler.bind(this);
}
submitHandler = () => {
//event.preventDefault();
};
changeRadioHandler = (event) => {
const id = event.target.value;
const question = { id, question: event.target.name };
if (
this.state.questions.some(
(question) => question.id === id || question.id !== id
)
) {
questions = [
...this.state.questions.filter(
(question) => question.id === id || question.id !== id
),
question,
];
} else {
questions = [...this.state.questions, question];
}
this.setState({ questions }, () => console.log(this.state.questions));
if (this.state.questions.length >= 9) {
this.setState({
buttonDisabled: false,
});
}
};
render() {
return (
<div class="matrix-bd">
{this.props.data.header_text && (
<div class="header-qn">
<h5>{this.props.data.header_text} </h5>
</div>
)}
{this.props.data.matrix && (
<div class="grid">
{this.props.data.matrix.option_questions.map((questions) => (
<div class="rows">
<div class="cell main">{questions.text}</div>
{this.props.data.matrix.options.map((element, i) => {
return (
<div class="cell" key={i}>
<input
type="radio"
id={i + questions.text}
name={questions.text}
value={element.text}
onChange={this.changeRadioHandler}
></input>
<label htmlFor={i + questions.text}>{element.text}</label>
</div>
);
})}
</div>
))}
</div>
)}
<div class="buttonsubmit text-right">
<button
type="button"
id="QstnSubmit"
name="QstnSubmit"
class="btn btn-primary"
disabled={this.state.buttonDisabled}
onClick={this.submitHandler}
>
Submit
</button>
</div>
</div>
);
}
}
export default MatrixBoard;
If the user is selecting or changing the selection after reaching the array limit, the array size should not change. And also the button enabling after reaching the size should not affect.