[React] Barcode/Barcode만료 구현

김민재·2023년 8월 29일

✔ JS바코드 사용 바코드 구현

✔ react에서 js바코드를 사용하기 위해서 패키지를 다운로드

using NPM

npm i react-jsbarcode

using yarn

yarn add react-jsbarcode

✔ 사용 예시 코드

✔ 바코드
import React,{useState} from 'react';

import JsBarcode from 'jsbarcode';

function Barcode() : React.ReactElement {
  const [barcode, setBarcode] = useState(''); // 바코드 변수 설정
  const [timeLeft, setTimeLeft] = useState(''); // 타임아웃 설정
  const [isExpired, setIsExpired] = useState(false); // 바코드 사용 시간 만료 설정
  const [isLoading, setIsLoading] = useState(false); // 더블클릭 방지용 

  
  const setBarcodeInfo = useCallback(() => {
    setBarcode(1700800045789999);
	setTimeLeft(180);
    // 해당 부부은 api가 있다면, 받아오는 역할의 const
  },[]);

  const handleClickRefreshBtn = () => {
    if (isLoading) return; //더블클릭 방지
    setIsLoading(true);
  };
  
  //타이머 만료 여부 확인
  const getIsExpired = useCallback((val: boolean) => {
    setIsExpired(val);
  }, []);


  useEffect(()=>{
    
    const generateBarcode = () => {
      if (barcode) {
        const barcodeString = 
              barcode.substring(0,4) + 
              '  ' + 
              barcode.substring(4,8) + 
              '  ' + 
              barcode.substring(8,12) + 
              '  ' + 
              barcode.substring(12,16);

        JsBarcode('#barcode-img', barcode, {
          backgroound: '#ffffff',
          text : barcodeString,
          height : 70,
          textAlign : 'center',
          fontSize : 15,
        });
      }
    };
    generateBarcode();
  }, [barcode]);
  
  
  return (
  	<section>
    	<div>
    		<h3>바코드</h3>
    		<div>
    			<svg id="barcode-img" width="270px" height="107px" /> 
    		</div>
    		{isExpired && (
			<div>
				<button onClick={handleClickRefreshBtn}><sapn>새로고침</span></button>
    		</div>
			)}
	    {isExpired ? (
         <p className={cx('txt_timer')}>인증 유효시간 초과</p>
         ) :
		 (
          <barCodeTimer
           timeLeft={timeLeft}
           getIsExpired={getIsExpired}
          />
        )}
    	</div>
  </section>
)

export default Barcode;
✔ 바코드 타이머
import React,{useState, useEffect} from 'react';

import { fillZero } from 'src/utills/utility';

interface Props {
	timeLeft : number;
	getIsExpired : (boolean) => void;
}

function BarcodeTimer(props: Props) : React.ReactElement {
  const [tiem, setTime] = useState({min : '', sec: ''});
  let seconds = props.timeLeft;
  
  const timer = seconds => {
    const min = Math.floor(seconds / 60).toString();
    const sec = fillzore(2, (seconds & 60).toString());
    return { min, sec };
  };
  
  useEffect(() => {
    if (seconds < 1) return;
    
    setTime(timer(seconds)); // 초기값 세팅
    
    const clear = setInterval(function () {
      if (seconds > 0) {
        seconds--;
        setTime(timer(seconds));
      } else {
        clearInterval(clear);
      }
    }, 1000);
    return () => {
      clearInterval(clear);
    };
  }, [props, seconds]);
  
  useEffect(() => {
    if (time.min === '0' && time.sec ==='00') {
      props.getIsExpired(true);
    }
   },[time, porps]);
  
  return (
  <p>남은 시간
    <span>
    	<em>{time.min} : {time.sec}</em>
	</span>
  </p>
  );
} 

export default BarcodeTimer;
* utility - fillZero 함수
/**
 * 숫자앞에 0 채우기
 * @param date  string
 */
export const fillZero = (width: number, str: string): string => {
  return str.length >= width
    ? str
    : new Array(width - str.length + 1).join('0') + str; //남는 길이만큼 0으로 채움
};
profile
주니어 개발자 (Front-End)

0개의 댓글