import { nanoid } from 'nanoid';
import React from 'react';
export default function Question(props) {
const answers = [...props.incorrect_answers, props.correct_answer];
const [selectedAnswer, setSelectedAnswer] = React.useState();
function handleChange(event) {
setSelectedAnswer(event.target.value);
console.log(event.target.value);
}
// Randomize answer of the Question
function createRandom(arr) {
let myArr = [...arr];
let randomizedArr = [];
while (myArr.length > 0) {
let randomIndex = Math.floor(Math.random() * myArr.length);
randomizedArr.push(myArr[randomIndex]);
myArr.splice(randomIndex, 1);
}
return randomizedArr;
}
const randomizedArr = createRandom(answers);
// RadioButton for the answers
const RadioButton = ({ label, value, onChange }) => {
return (
<label>
<input
type="radio"
name="answers"
value={value}
checked={selectedAnswer === value}
onChange={onChange}
/>
{label}
</label>
);
};
const answersElements = randomizedArr.map((answer) => {
return (
<RadioButton
key={nanoid()}
label={answer}
value={answer}
onChange={handleChange}
/>
);
});
return (
<div className="question-row">
<div className="single-question">{props.question}</div>
<div className="answers">{answersElements}</div>
</div>
);
}
When I select a radiobutton answer , React rerender the RaidoButton component and call my Randomize function which randomize the answers.
I do not know how to prevent Randomize function from being called after the first time.
in the two pictures when I select an answer for the first question , the answers get randomized again , I want to prevent this behavior
This is an XY question .
You need the component to be re-rendered when the state changes (if only to update which radio button is checked).
The problem is that you need the randomization function to run only on initial load.
Create a state for the random array:
const [randomizedArr, setRandomizedArr] = useState([]);Then populate it in an effects hook with an empty dependency array (so it only runs on initial load of the component).
useEffect(() => { const randomizedArr = createRandom(answers); setRandomizedArr(randomizedArr); }, []);const [randomizedArr, setRandomizedArr] = React.useState([]);
const [selectedAnswer, setSelectedAnswer] = React.useState();
React.useEffect(() => {
const answers = [...props.incorrect_answers, props.correct_answer];
const randomizedArr = createRandom(answers);
setRandomizedArr(randomizedArr);
}, [props.incorrect_answers, props.correct_answer]);