⚛️ React/문제풀기 (코딩애플: React)

React : 숫자가 아닌 걸 치면 alert 뜨는 input 만들기

Zoeeey 2023. 5. 26. 08:02

조건

input에 숫자가 아닌 문자를 치면 alert를 노출한다.


풀이

function Detail(props){
  let [alert, setAlert] = useState(true);
  let [amount, setAmount] = useState(true);
  let handleAmount = (e) => {
    let amount = e.target.value;
    if(isNaN(amount) === true){
      setAmount(false);
    } else {
      setAmount(true);
    };
  }
  return (
    <div className="container">
      { !amount && <Alertamount /> }
      <input id="amount" name="amount" onChange={ handleAmount } />
    </div> 
  )
}
function Alertamount(){
  return (
    <div className="alert alert-warning">
          숫자 외에 쓰지 마세요.
    </div>
  )
}

출처 : 코딩애플 https://codingapple.com/