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;
@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;
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