Home > Net >  Display random text in React app with Math.random()
Display random text in React app with Math.random()

Time:10-26

I previously had embedded this JS code inside an HTML page with this:

    <SCRIPT LANGUAGE="JAVASCRIPT">
    var r_text = new Array (); 
    r_text[0] = "\"This is a test\""; 
    r_text[1] = "\"This is another\""; 
    r_text[2] = "\"This is a test\""; 
    r_text[3] = "\"This is another\""; 
    var i = Math.floor(r_text.length * Math.random()); 
    
    document.write("<center>"   
    r_text[i]    "</center>"); 
    </SCRIPT>

It allows me to define a bunch of sentences and have a random one displayed each time the page loads.

I am now re-doing my site as a React app (and using TailwindCSS FWIW).

I tried dropping it directly like below:

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div class="container mx-auto">

      <div class="max-w-md mx-auto bg-white text-center text-6xl m-10 overflow-hidden md:max-w-2xl">
      site title
      </div>
    
    var r_text = new Array (); 
    r_text[0] = "\"This is a test\""; 
    r_text[1] = "\"This is another\""; 
    r_text[2] = "\"This is a test\""; 
    r_text[3] = "\"This is another\""; 
    var i = Math.floor(r_text.length * Math.random()); 
    
    document.write("<center>"   
    r_text[i]    "</center>"); 

This is not working, but I'm not sure how to make it compile.

CodePudding user response:

In ReactJS, it is advisable to perform all calculations before rendering the content. I advise you to read the React documentation

import { useState, useEffect } from "react";

function App() {
  const [text, setText] = useState("");

  useEffect(() => {
    let r_text = new Array();
    r_text[0] = '"This is a test"';
    r_text[1] = '"This is another"';
    r_text[2] = '"This is a test"';
    r_text[3] = '"This is another"';

    var i = Math.floor(r_text.length * Math.random());
    setText(r_text[i])
  },[])

  return (
    <div class="container mx-auto">
      <div class="max-w-md mx-auto bg-white text-center text-6xl m-10 overflow-hidden md:max-w-2xl">
        site title
      </div>
      <p>{text}</p>
    </div>
  );
}

export default App;
  • Related