Skip to main content

CSS nth-child 이용해서 랜덤처럼 보이게 구현하기


사실 자바스크립트를 이용하면 간단하게 랜덤을 구현할 수 있다.

하지만 아래 두 가지를 만족하는 상태에서 각 요소에 대해 랜덤을 구현하는것은 까다롭다.

  • javscript 코드 변경 금지
  • 요소가 얼마나 만들어질지 모름

아래는, 순수하게 css만 이용하여 랜덤하게 보이도록 구현하는 방법이다.

[React] input 유효성 검증 및 helper text 표시하기


리액트에서 useStateuseRef를 사용하여 input text의 유효성을 검증하고 helper text를 표시하는 방법입니다.



변수 및 함수 설명

  • updateData : input값을 inputData에 저장하는 함수
  • checkValidation : 이메일 또는 비밀번호 양식이 맞지 않는 경우, helperText를 표시하는 함수
  • handleChange : input값이 변경될때 실행되는 함수 (updateData, checkValidation 함수 실행)


useState vs useRef

렌더링이 필요없는 email, passworduseRef를 사용하였고, 렌더링이 필요한 helperTextuseState를 사용했습니다.

코드

Live Editor
function App() {
  const inputData = useRef({
    email: '',
    password: '',
  });

  const [helperText, setHelperText] = useState({
    email: false,
    password: false,
  });

  const updateData = (id, value) => {
    inputData.current[id] = value;
  };

  const checkValidation = (id, value) => {
    const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    const passwordRegex =
      /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,16}$/;
    const regex = id === 'email' ? emailRegex : passwordRegex;

    regex.test(value)
      ? setHelperText({ ...helperText, [id]: false })
      : setHelperText({ ...helperText, [id]: true });
  };

  const handleChange = (event) => {
    const { id, value } = event.target;
    checkValidation(id, value);
    updateData(id, value);
  };

  return (
    <>
      <input id="email" onChange={handleChange} />
      <span>{helperText['email'] && '이메일 형식을 맞춰주세요.'}</span>
      <br />

      <input id="password" onChange={handleChange} />
      <span>
        {helperText['password'] &&
          '비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요.'}
      </span>
    </>
  );
}
Result
Loading...


참고자료