How to store radio button values in ascending order of index in an array in react?
let questions;
class App extends Component {
constructor(props) {
super(props);
this.state = {
btnDisabled: true,
questions: [],
};
this.changeRadioHandler = this.changeRadioHandler.bind(this);
this.submitHandler = this.submitHandler.bind(this);
}
changeRadioHandler = (event) => {
const qn = event.target.name;
const id = event.target.value;
let text = this.props.data.matrix.options;
let userAnswer = [];
for (let j = 0; j < text.length; j++) {
userAnswer.push(false);
}
const option = text.map((t, index) => ({
text: t.text,
userAnswer: userAnswer[index],
}));
const elIndex = option.findIndex((element, i) => element.text === id);
let options = [...option];
options[elIndex] = {
...options[elIndex],
userAnswer: true,
};
const question = {
id: event.target.value,
qn,
options,
};
if (this.state.questions.some((question) => question.qn === qn)) {
questions = [
...this.state.questions.filter((question) => question.qn !== qn),
question,
];
} else {
questions = [...this.state.questions, question];
}
console.log(questions);
this.setState({ questions });
if (questions.length === text.length) {
this.setState({
btnDisabled: false,
});
}
};
submitHandler = () => {
console.log("btn clkd", questions);
};
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, j) => {
return (
<div class="rows" key={j}>
<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={"rad" + j + i}
name={questions.text}
value={element.text}
onChange={this.changeRadioHandler}
></input>
<label htmlFor={"rad" + j + i}>{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.btnDisabled}
onClick={this.submitHandler}
>
{this.props.labels.LBLSUBMIT}
</button>
</div>
</div>
);
}
}
export default App;
I have added my code where the array is unordered with respect to index, I want to order the array using qn(const qn = event.target.name;) object. Like, how it came from the database, likewise in the same order, it should go into the db.