0

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);
 }
3
  • You call add a onClick={randomScenario} to your button? Commented Aug 17, 2022 at 7:43
  • @GabrielPichot, he wants to know the way to make setIndex() as well. Commented Aug 17, 2022 at 7:53
  • Then something const [index, setIndex] = React.useState(0); and then const item = array[index] should work no? Commented Aug 17, 2022 at 7:54

2 Answers 2

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

It's TS version FYI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.