sayinmehmet47
sayinmehmet47

Reputation: 551

Why I can`t set background color by using setcolor?

I have a function that procude random color. I want to take this random color everytime i click on button.I tried to set the color **setBgColor(random_bg_color())**But it gives error like this.Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. How can i call my random color function and set in hook?

import React, {useContext } from 'react';
import {GeneralContext} from "./App"


export default function Theme() {


    function random_bg_color() {
        var x = Math.floor(Math.random() * 120);
        var y = Math.floor(Math.random() * 120);
        var z = Math.floor(Math.random() * 120);
        const rgb = 'rgb(' + x + ',' + y + ',' + z + ')';
        return rgb;
      }
      




const {value,value2,value3}=useContext(GeneralContext)
const [text, setText] = value;
const [author,setAuthor] = value2;
const [bgColor,setBgColor]=value3
setBgColor(random_bg_color())







    return (
        <div>
            <p>{bgColor}</p>
            <p>{author}</p>
        </div>
    )
}


Upvotes: 0

Views: 103

Answers (2)

Medi
Medi

Reputation: 1036

create a handler and pass it to the onClick of your button

const handleClick = ()=>{
  setBgColor(random_bg_color());
}

Upvotes: 1

voxtool
voxtool

Reputation: 355

If you want to set it once when the component renders you can use the useEffect hook.

useEffect(() => {
  setBgColor(random_bg_color());
},[])

The empty array which is the second parameter of the useEffect hook ensures that this code will run when the component mounts.

Upvotes: 2

Related Questions