Home > other >  Shuffle Array click handler event help React
Shuffle Array click handler event help React

Time:11-06

So I have the following code that shuffles an array and returns a pair of words

const words = 
  [ 'monitor', 'program', 'application', 'keyboard'
  , 'javascript', 'gaming', 'network'
  ]
for (let i = words.length; --i;)  // shuffle Array
  {
  let j = Math.floor(Math.random() * (i   1));
  [words[i], words[j]] = [words[j], words[i]]
  }

// get 2 random words
console.log( words[0], words[1] )

I want to return each word in its own button like the following picture: Each time a button is selected with an onClick I want the page to rerender with a new set of questions. How can I do this in React? enter image description here

CodePudding user response:

A simple version of the App, without the CSS would look like:

import React, { useState } from 'react';

const defaultWords = [ 'monitor', 'program', 'application', 'keyboard', 'javascript', 'gaming', 'network']

const App = () => {

    const [words, setWords] = useState(defaultWords);

    const shuffleWords = () => {
        for (let i = words.length; --i;)  {
            let j = Math.floor(Math.random() * (i   1));
            [words[i], words[j]] = [words[j], words[i]]
        }
        setWords([...words]);
    }

    return (
        <div>
            <button onClick={shuffleWords}>{words[0]}</button>
            <button onClick={shuffleWords}>{words[1]}</button>
        </div>
    );
}

export default App;

You can try the code on codesandbox: https://codesandbox.io/embed/sparkling-sunset-bstk7?fontsize=14&hidenavigation=1&theme=dark

CodePudding user response:

I would use the useEffect and useState hooks to create an array of the randomly selected words.

Say for example the first argument of the useState hook is randomWordPair, I would then create a function the would render the buttons using something like:

const renderWordButtons = () => { 
  return randomWordPair.map((word) => {
      return (<button onClick={(e) => handleOnClick(word)}>{word}</button>)
    )
  })
}

Then you would call that function in the return of the component.

  • Related