button color change loop in react 1

button color change loop in react

import React, { useState } from "react";

export default function App() {
  const Colors = ["red", "green"];
  return (
    

Hello CodeSandbox

Start editing to see some magic happen!

{Colors.map((color, key) => (
); } function Button({ Color, Colors }) { const [color, setColor] = useState(Color); const handleChange = (e) => { e.preventDefault(); setColor(Colors[Math.floor(Math.random() * Colors.length)]); }; const style = { backgroundColor: color }; return ( ); }

Here is what the above code is Doing:
1. We have a Colors array that contains two colors.
2. We map over the Colors array and pass the color and the Colors array to the Button component.
3. In the Button component, we use the useState hook to set the color state to the color passed in from the App component.
4. We create a handleChange function that sets the color state to a random color from the Colors array.
5. We create a style object that sets the background color to the color state.
6. We return a button that has an onClick event that calls the handleChange function and a style attribute that sets the background color to the color state.

Similar Posts