Search code examples
arraysreactjsreact-hooksreact-componentreact-functional-component

React Custom Roulette how to show the roulette number


enter image description here

> - - DEMO CODE - - <

The problem is to show the number when the roulette wheel is stopped.

const data = [
  { id: 1, option: 10 },
  { id: 2, option: -30 },
  { id: 3, option: 50 },
  { id: 4, option: 30 },
  { id: 5, option: 40 },
  { id: 6, option: 20 }
];

export default () => {
  const [mustSpin, setMustSpin] = useState(false);
  const [prizeNumber, setPrizeNumber] = useState(0);

  const handleSpinClick = () => {
    const newPrizeNumber = Math.floor(Math.random() * data.length);
    setPrizeNumber(newPrizeNumber);
    setMustSpin(true);
  };

  return (
    <>
      <div align="center">
        <h1 align="center">Roulette Game</h1>
        <hr />
        <Wheel
          mustStartSpinning={mustSpin}
          prizeNumber={prizeNumber}
          data={data}
          outerBorderColor={["#f2f2f2"]}
          outerBorderWidth={[25]}
          innerBorderColor={["#f2f2f2"]}
          radiusLineColor={["#dedede"]}
          radiusLineWidth={[10]}
          textColors={["#ffffff"]}
          fontSize={[50]}
          perpendicularText={[true]}
          backgroundColors={[
            "#F22B35",
            "#F99533",
            "#24CA69",
            "#514E50",
            "#46AEFF",
            "#9145B7"
          ]}
          onStopSpinning={() => {
            setMustSpin(false);
          }}
        />
        <button className="button2" onClick={handleSpinClick}>
          SPIN
        </button>
        <br />
        {data.option}
        <hr />
      </div>

I entered this code above but it shows the const data array id = [{ id: 1, option: 10 },{ id: 2, option: -30 },{ id: 3, option: 50 },{ id: 4 , option: 30 },{ id: 5, option: 40 },{ id: 6, option: 20 } ];

I try this but fail

{data.option}

Solution

  • data is an array, so it likely won't have an option property.

    It seems prizeNumber is the psuedo-random index, so to display the option access it from the data array.

    {data[prizeNumber].option}