lundi 3 octobre 2022

React- Want to keep random options in a quiz app but the page keeps re-rendering upon using the button click

I have tried to keep this code as simple as possible to test the behaviour that is happening in react app component.

ISSUE: I have used random number generator to get a value and then divide by 2, to get remainder of 0 or 1, there are two buttons and the text in it would be displayed basing on the remainder. However, there is an onClick function to both buttons and upon clicking sometimes the text value in the button interchanges, which happens because the value of 0 or 1 changes upon clicking the button. Does the app component re-render from line0 upon clicking the button?, if not why does initially it takes in a value(0/1) and then might change upon click of a button ?. Images of the issue have been added for better understanding.

Here is the code:

    import { useState } from 'react';
    import './App.css';

    function App() {
    const i = Math.floor(Math.random() * 9);
    const index = i%2;
    const a ="button1"
    const b= "button2"
    const [image,setImage] = useState(false);
    return ( 
    <div className="App">
    <h1>{index}</h1>
    <button onClick={()=>setImage(true)}>{(index===0)?(a):(b)}</button>
    <button onClick={()=>setImage(true)}> {(index===0)?(b):(a)} </button>
    </div>
       );
    }

    export default App;

Case0 on top[before pressing button] : enter image description here

Case1 on top[I have pressed button1 from first case] :enter image description here

I want the buttons to be random and also to stay that way after I have clicked the button. Any insights on this will be appreciated.




Aucun commentaire:

Enregistrer un commentaire