0

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Wait that actually fixed it! My bad thought I needed to put emailBgColor in curly braces. Is it because emailBgColor is not a JSX component?
No."backgroundColor" property accepts only the data of type "string". But you were passing an "object".
1

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 }}
/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.