A working example for you is:
import React, { useState } from "react";
export default function App() {
const Colors = ["red", "green", "blue", "orange", "yellow"];
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{Colors.map((color, key) => (
<Button Color={color} Colors={Colors} key={key} />
))}
</div>
);
}
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 (
<button onClick={handleChange} style={style}>
Click Me!
</button>
);
}
Demo: https://00qh5.csb.app/
Preview

Previous Answer:
You have an error, if you're not using ()
after return statement. It becomes Automatic Semicolon Insertion in JavaScript in JavaScript and it will not work. So don't leave the return
statement hanging.
You're supposed to use state only for those things that'll change. Not for storing variables.
Also, I would avoid using fragments <></>
here as it doesn't make any sense. So I removed that as well.
The onClick={changeBtncolor(props)}
will execute the changeBtncolor(props)
immediately, so you need to wrap it inside a handler function.
You're not passing any value to the setColour
function inside the changeBtncolor
function, but you're passing props
, which there's no clarity, so I have changed the way the function now works, by using a colour name instead from the props
.
Notice the difference between color
and the prop colour
. Here's an updated React code that will work as per your expectations.
import React, { useState } from "react";
export default function Button({ colour }) {
const [colors, setColour] = useState([
"red",
"green",
"blue",
"orange",
"yellow"
]);
const changeBtncolor = color => {
setColour(color);
};
return colors.map((color, id) => (
<Button
key={id}
type="button"
style={{ backgroundColor: color }}
onclick={() => changeBtncolor(colour)}
>
Change color
</Button>
));
}