javascriptreactjsreact-hooksbuttonclick

Change text on button depending on value of a number - React using Hooks


I have a counter that is the index of my array, on every button click the next element is showing. What I want to achieve is I want a specific text to show on the beginning and when index becomes 0 again and a different text on the in between numbers. Here is my code till now, the text stays the same but I am not sure what is wrong.

function App() {


const questions_size = Data.length; 
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  const [buttonText, setButtonText] = useState("Παιξε");
  const change_text = (text) => setButtonText(text);

  const callTwoFunc = () => {
    setNum(num + 1);
    setButtonText("Επομενο");
  }

  return (

  <div style={{ display: 'flex' }}>

          <Button variant="contained" color="primary" onClick={() => {  num < questions_size - 1 ? callTwoFunc() : setNum(0); change_text("Παιξε"); }}>{buttonText}</Button>
          <Card className={classes.root}>
            <CardContent>

              <Typography variant="body1" gutterBottom>

                <p style={{ fontFamily: 'Tangerine, serif', fontSize: '35px', textShadow: '4px 4px 4px #aaa' }}>{current}</p>
              </Typography>
            </CardContent>
          </Card>



  </div>


  );
}

export default App;

For now it's only saying "Παιξε" but i want it become "Επόμενο" after my first click, and then when num becomes zero to become "Παίξε" again.


Solution

  • The problem is the change_text('Παιξε'); part of your onClick function of the Button:

    onClick={() => {
        num < questions_size - 1 ? callTwoFunc() : setNum(0);
        change_text('Παιξε');
      }}
    

    It will always change the button to Παιξε. It is easier to move that logic into callTwoFunc:

    const callTwoFunc = () => {
        setNum(prev => {
         if(prev < questions_size - 1) {
           return prev + 1;
         } else {
           return 0;
         }
       })
      }
    

    And for the button as there are only two states, it is easier to do it directly instead of using state:

    <Button>{num === 0 ? "Παιξε" : "Επομενο" }</Button>