Maggie Mao
Maggie Mao

Reputation: 187

ReactJS color not updating

So bacially, I've been trying to implement a method to change the email input background to red if it is not valid, and green if it is. Here's my code:

var bgColors = { "default": "green",
                 "error": "red",
};

const SignUp = ({ history }) => {
    // Irrelevant methods skipped...
    const [emailBgColor, setEmailBgColor] = useState (
        bgColors.default
    );

    /* When input for email address changes, try to validate the email address */
    const handleEmailChange = (event) => {
        const emailInput = event.target.value;
        let lastAtPos = emailInput.lastIndexOf('@');
        let lastDotPos = emailInput.lastIndexOf('.');
        let validFormat = lastAtPos > 0 && lastDotPos > 2 && lastAtPos < lastDotPos;

        // Tries validating email address here
        if(emailInput === "" || !validFormat) {
            console.log("Invalid email"); // This line logs correctly
            setEmailBgColor(bgColors.error);
            console.log({emailBgColor}); // This line also logs correctly
        }
        else{
            setEmailBgColor(bgColors.default);
        }
    };

    return(
        <input onChange={handleEmailChange}
         style={{backgroundColor: {emailBgColor}}}
        /> {/*Does not work, does not even show the default green color*/}
    )
}

Which as the comments in the code suggested, does not update the colors despite console.log indicates that the emailBgColor has changed.

I tried doing style={{backgroundColor: "blue"}} and that apparently works. I wonder what could be the cause? Thanks.

Upvotes: 0

Views: 1250

Answers (2)

imran haider
imran haider

Reputation: 343

Replace your code with following. emailBgColor is not an object property, it is a string. You see const bgColors = { default: "green", error: "red" }; is an object but bgColors.default is a string which you are setting in setEmailBgColor

<input
  onChange={handleEmailChange}
  style={{ backgroundColor: emailBgColor }}
/>

Upvotes: 1

Edison D&#39;souza
Edison D&#39;souza

Reputation: 4640

I think the syntax you have used is incorrect. Have you tried backgroundColor: emailBgColor?

Upvotes: 3

Related Questions