Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!