This example simulates a coin toss.
I would like to randomize the initial state of the coin. The first time the page is loaded it could show heads. The next time, tails. To do so, I am using a random number generated by the Math method and a conditional to determine the face of the coin based on the random number (even number shows heads, odd shows tails).
The value needs to be displayed upon the initial render.
I also want to store the value in state using React's Hooks to use later in my app. How can I set a randomized initial state value using hooks?
Here is the code that I am working with. It currently does not function and I'm not sure what I am doing incorrectly to achieve my goal:
import React, { useState } from 'react';
import './App.css';
function App() {
const [coin, setCoin] = useState(randomizePlayer())
const randomizePlayer = () => {
let number = Math.floor(Math.random() * 10) + 1
return (number % 2 === 0) ? setCoin('Heads') : setCoin('Tails')
}
return (
<div className="App">
The coin is showing {coin}
</div>
);
}
export default App;
I'm brand new to the hooks API and am using this exercise to learn.
Any help is appreciated!