skip to Main Content

username state

const [username, setUsername] = useState({
    name: "",
    isValid: true,
    error_message:
      "start with a letter n allowed characters: a-z A-Z 0-9 - and _ ",
  });

handle username function

  function handleUsername(e) {
    const regexp = new RegExp(/[a-zA-Z][a-zA-Z0-9-_]{5,32}/gi);
    const name = e;
    const isValid = regexp.test(name);
    setUsername(() => {
      return {
        name: name,
        isValid: isValid ? true : false,
      };
    });
  }

jsx.

<div className={`error ${username.isValid ? "hidden" : ""}`}>
                {username.error_message}
              </div>

How can I show the div depending on the username.isValid state, it seems like the condition in the className of the div doesn’t react to the state changes.

2

Answers


  1. Chosen as BEST ANSWER

    The confusions is I just forgot to destructure the object when setting the new state into handleUsername function:

    function handleEmail(e) {
        const regexp = new RegExp(
          /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{1,}))$/
        );
        const currentEmail = e;
        const isValid = regexp.test(currentEmail);
        setEmail(() => {
          return {
            ...email,
            address: currentEmail,
            isValid: isValid ? true : false,
          };
        });
      }
    

  2. You can use ternary operator if username.isValid is falsy value then it will render else not as:

      {!username.isValid ? (
        <div className="error">
          {username.error_message}
        </div>
      ) : null}
    

    You can see this CODESANDBOX

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search