Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda