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

90
Vistas
React | how to display random string from array and choose another random on btn press

So I'm learning react and wanted to make an idea generator that would pull a string from an array (the 'researchTitles') file, and display it in the h1 and then on the button click it would pick another at random and display that. so far I've just got the outline and the method to pick a string at random, is there a better way to do this? and if so can I get some help

import researchTitles from './
import React from 'react';

function App() {

  const title = researchTitles[Math.floor(Math.random() * researchTitles.length)];
  
  return (
    <div className="App">
      <h1>{title}</h1>
      <button onClick={}>Generate</button>
    </div>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

@Terry explained it exactly. Here is a real-world example:

import React, { useState } from "react";

const researchTitles = [
  "AI",
  "Machine Learning",
  "Data Science",
  "Metaverse",
  "Crypto",
  "Tech"
];

const getRandomResearchTitle = () => {
  return researchTitles[Math.floor(Math.random() * researchTitles.length)];
};

function App() {
  const [researchTitle, setResearchTitle] = useState(getRandomResearchTitle());
  const handleClick = () => {
    // shuffle array and pick random
    const randomResearchTitle = getRandomResearchTitle();
    setResearchTitle(randomResearchTitle);
  };

  return (
    <div className="App">
      <h1>{researchTitle}</h1>
      <button onClick={handleClick}>Generate</button>
    </div>
  );
}

export default App;


about 4 years ago · Juan Pablo Isaza Denunciar

0

Why don't you created a function generate() that do this word picking? So every time that you click teh button

<button onClick="generate()">Generate</button>

it will pick some word and return it on h1 element?

You could use document.createElement() inside your function

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