Home > Software engineering >  React Slide Animation removing selected value on unmountOnExit
React Slide Animation removing selected value on unmountOnExit

Time:06-03

I am facing a issue, on click of radio button the next question comes using slide animation, But on unmounting on Exit the previously selected radio button value is also getting deselected. How to prevent this from happening.

const Quiz = (props) => {
     const {questions, quiz, options} = useSelector((state) => state.quiz);
  
    const [user, setuser] = useState("");
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [checked, setChecked] = useState(true);  
    const [option, setOptions] = useState("");
    
    const dispatch = useDispatch();
    const history = useHistory();

 const handleRadioChange = (number, event) => {
  
    let currentSelection = questions.find(question => question.number === number);
    console.log(currentSelection   "radio selected");
    currentSelection.value = event.target.value;
  
    questions[currentQuestion].value = event.target.value;
   
    console.log(questions[currentQuestion].value   "value added");
    setCurrentQuestion((current) => {
      return Math.min(
        current   1,
        questions.length - 1
      );
    });
      setChecked((previousState) => !previousState);
      setTimeout(() => { 
        setChecked(previousState => ({
             afterPreviousChange: previousState.previousChange 
           }))
      }, 1000);
    
};


    const previousQuestion = (event) => {
        event.preventDefault();
        let new_current_questions = Math.max(currentQuestion - 1, 0);
        setCurrentQuestion(new_current_questions);
        setChecked((previousState) => !!previousState);
       const a =  setTimeout(() => { 
          setChecked(previousState => ({
               afterPreviousChange: previousState.previousChange 
             
             }))
        }, 1000);
       
      };
 function handleSubmit(event) {
        event.preventDefault();     
        const valid = questions.some((q) => !q.value);
        console.log(valid   "questionsalpha");
        if (!valid) {
            dispatch(postQuiz({ responses: questions, id: quiz.id }, history));
        }
        setChecked((previousState) => !previousState);
        const a =  setTimeout(() => {                
            setChecked((previousState) => !previousState);   
            setCurrentQuestion(0);
              },1000);};
    return(

      <Slide direction="up"  
        in={checked} 
        appear={true} 
        mountOnEnter 
                 unmountOnExit
        timeout={{ enter: 1000 , exit: checked ? 1 : 900}}
    >   
            <Card variant="outlined" sx={{ bgcolor: "#bea"}} elevation={0}>
                <CardContent>
    
                <form onSubmit= {handleSubmit}>
                        <CardActions>
                      <Button type="submit" color="warning" variant="outlined" disabled={currentQuestion===0} className={classes.button} onClick={previousQuestion}>
                          Previous</Button>
                      </CardActions>              
                      <FormControl component='fieldset' className={classes.formControl}
        data-hidden={questions[currentQuestion].number !==
          currentQuestion[questions[currentQuestion].number]} >
        <FormLabel component='legend'>
          {questions[currentQuestion].question}
        </FormLabel>
        <FormLabel component='legend'>
          {questions[currentQuestion].description}
        </FormLabel>
        <RadioGroup
          aria-label='quiz'
          name='quiz'
          defaultValue={' '}
          value={questions[currentQuestion].value}
          checked={checked}
          onChange={(e)=> handleRadioChange(questions[currentQuestion].number, e)}
          sx={{
            color: pink[800],
            '&.Mui-checked': {
              color: blue[600],
            },
          }}>
          {options.map((option) => (
            <FormControlLabel
              key={option.score}
              value={option.score}
              control={<Radio  sx={{
                color: pink[800],
                '&.Mui-checked': {
                  color: blue[600],
                },
              }}/>}
              label={option.label}
             
            />
          ))}
        </RadioGroup>
      </FormControl>
                        <CardActions>
                        <Button type="submit" variant="contained" color="primary" className={classes.button} disabled={currentQuestion<5} onClick={handleSubmit}>
                        Submit
                    </Button>
                  </CardActions>
                    </form>
                    </CardContent>
                    </Card>
                    </Slide>
      );

function using handleChange and previous button is also I have shared. Please help with this issue.

CodePudding user response:

The main reason for previously radio button value not persist is because you are not changing the questions state with the update values, you are just changing the object itself.

The error is specifically here:

let currentSelection = questions.find(question => question.number === number);

console.log(currentSelection   "radio selected");

// HERE YOU ARE CHANGIG ONLY THE OBJECT, NOT THE ARRAY
currentSelection.value = event.target.value;
  
questions[currentQuestion].value = event.target.value;

One way to do this is map the questions array, change the current question value and then update the questions state:

const updatedQuestions = questions.map((item) => {
   if (item.number === currentQuestion) item.value = event.target.value;
      return item;
   });

setQuestions(updatedQuestions);

But your code also have other inconsistencies, i did a code sample for you with comments.

  • Related