'How do I change the background color of the container using onClick?
I am using Next.js. I have a set of colors in a different file. How do I change the background color randomly when clicking the button?
The Color.js
file
export const Colors = [
"#16a085",
"#27ae60",
"#2c3e50",
"#f39c12",
"#e74c3c",
"#9b59b6",
"#FB6964",
"#342224",
"#472E32",
"#BDBB99",
"#77B1A9",
"#73A857",
];
The Main file
import { Colors } from "./Colors.js";
export default function Home() {
const randomColor = Math.floor(Math.random() * 12);
const [color, setColor] = useState(Colors);
console.log(color);
const changeColor = () => {
setColor(color[randomColor]);
};
The Error:
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading '9')
Solution 1:[1]
You have made 3 mistakes in your code.
First you have created color
state with whole color array that you have imported.
But instead use one default or empty value as below
const [color, setColor] = React.useState("#16a085");
The next mistake is to you are fetching index from the state color
which is not an array once you click on the button it becomes a string and it will index out of bound as no color string has length greater than 7
It can be fixed by
setColor(Colors[randomColor]);
Now you will get rid of the error but the color won't change because your random number generator is outside and it is generate when the component updates so fix will be to place it inside the function.
The final code I guess will look as below
import { Colors } from "./Colors";
export default function App() {
const [color, setColor] = React.useState("#16a085");
const changeColor = () => {
const randomColor = Math.floor(Math.random() * 12);
setColor(Colors[randomColor]);
};
return (
<div className="App">
<div style={{ color: color }}>hello</div>
<button onClick={changeColor}>change</button>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sahil Paudel |