Home > front end >  How to change the style of input element in react
How to change the style of input element in react

Time:11-04

i have this input component:

enter image description here

I want to change the style of input component if the value of input is less than the current year. for example, if the user entered 2020 which is less than 2022, in this case i want to change the color of background for example. Any help will be appreciated

A function will be called to check the entered value and whether we need to change the style or not:

let changeStyle=false;
  
const checkExpireYear = (year: string) => {
    
    // converting the entered year to number
    let enteredYear: number = parseInt(year);
    
    // getting the current year
    const date = new Date();
    let currentYear = date.getFullYear();
    // checking if the entered year is less than the current year
    // based on this condition the style will be changed
    if (enteredYear > currentYear) {
      console.log("valid year");
      changeStyle = false;
    } else {
      console.log("unvalid year");
      changeStyle = true;
    }
  };

and this is my input component :

<CardNumberInput
                className={changeStyle ? "bg-red-400" : ""}
                placeholder="2030"
                onChange={(e) => {
                  if (e.currentTarget.value.length > 3) {
                    checkExpireYear(e.currentTarget.value);
                  }
                }}
/>

it does not show any error, but the style is not changing
Thanx in advance

CodePudding user response:

It is because you are not using useState hook for the changeStyle variable

import {useState} from "react";

const [changeStyle, setChangeStyle] = useState(false);
  
const checkExpireYear = (year: string) => {
    
    // converting the entered year to number
    let enteredYear: number = parseInt(year);
    
    // getting the current year
    const date = new Date();
    let currentYear = date.getFullYear();
    // checking if the entered year is less than the current year
    // based on this condition the style will be changed
    if (enteredYear > currentYear) {
      console.log("valid year");
      setChangeStyle(false);
    } else {
      console.log("unvalid year");
      setChangeStyle(true);
    }
  };

Now it should work with no error. When we use useState every time the state of the variable gets changed when we call setChangeStyle, it re-renders the component with new state, which does not happen when you just use let changeStyle

CodePudding user response:

your "changeStyle" variable, should be a state variable. this way, every time that its value changes makes that component re-render and applies other CSS class to it

  • Related