Home > Mobile >  Change box color randomly when button is clicked
Change box color randomly when button is clicked

Time:03-05

I want to change color of box randomly when button is clicked. But when I click on button background becomes white. I dont know the reason i am color flipper project and got stuck here. I checked console their color values are generating but it is not getting assigned to background-color: property.

import React,{useState} from 'react'
import styled from 'styled-components'

function Box() {
    function randomRGB(){
        // console.log("random");
        return Math.floor(Math.random() * 256);
    }
    function getRandomColor() {
        const color ='rgb('   randomRGB()   ','   randomRGB()   ','   randomRGB()   ')';
        console.log(color);
        return color;
    }
    var [currentColor, setCurrentColor] = useState(getRandomColor());
  return (
    <div>
        <BoxC back={currentColor}></BoxC>
        <Div onClick={setCurrentColor}>Button</Div>
    </div>
  )
}
var BoxC = styled.div`
    width: 200px;
    height: 200px;
    background: ${(props) => props.back};
`
const Div = styled.button`
    width: 70px;
    height: 50px;
    border: 2px solid green;
    cursor: pointer;
`
export default Box

CodePudding user response:

You have to assign a new color on click by

onClick={()=>setCurrentColor(randomrgb())}>Button</Div>

CodePudding user response:

You are not setting the currentColor state to anything. You are just calling the function.

Do it like this instead:

import React,{useState} from 'react'
import styled from 'styled-components'

function Box() {
var [currentColor, setCurrentColor] = useState(getRandomColor());
    function randomRGB(){
        // console.log("random");
        return Math.floor(Math.random() * 256);
    }
    function getRandomColor() {
        const color ='rgb('   randomRGB()   ','   randomRGB()   ','   randomRGB()   ')';
        console.log(color);
        return setCurrentColor(color);
    }
  return (
    <div>
        <BoxC back={currentColor}></BoxC>
        <Div onClick={() => getRandomColor()}>Button</Div>
    </div>
  )
}
var BoxC = styled.div`
    width: 200px;
    height: 200px;
    background: ${(props) => props.back};
`
const Div = styled.button`
    width: 70px;
    height: 50px;
    border: 2px solid green;
    cursor: pointer;
`
export default Box
  • Related