Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
Shuffle Array click handler event help React

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda