Home > Software engineering >  How to display random and unique object from array on click
How to display random and unique object from array on click

Time:08-17

The below function will display a random object from the array, passing the index number to setIndex(index). I want to display a random and unique object. How do I achieve this?

const length = array.length
const randomScenario = () => {
    const index = Math.floor(Math.random() * length);
    setIndex(index);
 }

CodePudding user response:

You're doing great but you've missed useState to achieve this.

Here's a little example:

import React, { useState } from 'react';

export function App() {

  const array = ["hi", "bye", "etc..."];
  const [index, setIndex] = useState();
  const length = array.length

  const randomScenario = () => {
    const index = Math.floor(Math.random() * length);
    setIndex(index);
  }

  return (
    <div>
      <button onClick={() => {randomScenario()}}>
        Click Me
      </button>
      <p> {!index && index !== 0 ? 'Click to see magic' : array[index]} </p>
    </div>
  );
}

CodePudding user response:

import React from "react";

const arr = ["car", "truck", "crane", "ship"];
const length = arr.length;

export default function Home() {
  const [word, setWord] = React.useState<string>("");
  const randomScenario = () :void => {
    const index = Math.floor(Math.random() * length);
    setIndex(index);
  };

  const setIndex = (index: number): void => {
    setWord(arr[index]);
  };
  return (
    <div>
      <p id="show-object">{word}</p>
      <button onClick={randomScenario}>Click me</button>
    </div>
  );
}

Here is the code snippet as an answer.

  • Related