0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.