본문 바로가기
front-end/React

[React] 천단위마다 쉼표 넣는 방법

by -제이리 2022. 5. 23.
728x90
320x100

금액을 입력하기위해 1,000단위마다 ,(콤마)를 찍어주는 방법을 찾아보는데

아래 사이트에서 npm만 설치하면 자동으로 콤마가 찍히는 아주 기똥찬 패키지를 발견했다. 개꿀~~!!

 

https://www.npmjs.com/package/react-currency-input-field

 

react-currency-input-field

React <input/> component for formatting currency and numbers.. Latest version: 3.6.4, last published: 4 months ago. Start using react-currency-input-field in your project by running `npm i react-currency-input-field`. There are 40 other projects in the npm

www.npmjs.com

 

npm 설치하기

npm install react-currency-input-field

// 설치가 안되면 아래방법으로 설치하기
npm install react-currency-input-field --save --legacy-peer-deps

 

사용방법

1. import 해주기

2. input 태그를 CurrencyInput로 바꿔주기

3. 경우에따라 프롭스사용

import CurrencyInput from 'react-currency-input-field';

<CurrencyInput
  id="input-example"
  name="input-name"
  placeholder="Please enter a number"
  defaultValue={1000} //디폴트값 입력 
  decimalsLimit={2} //소수점 
  onValueChange={(value, name) => console.log(value, name)}
/>;

 

이렇게 패키지를 다운받거나 

 

 

정규식을 함수를 만들어 사용하는 방법이 있다. (string 타입)

function priceToString(price) {
    return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

 + 콤마 없애기 (number 타입으로 변환할때)

function stringToPrice(str) {
    return Number(str.replace(/,/g, ""));
}
728x90
320x100

'front-end > React' 카테고리의 다른 글

Json-server 사용하기 (REST API 구축 라이브러리)  (0) 2022.06.15
[React]git hub배포하기  (0) 2022.05.28
[React] Fragments 란?  (0) 2022.05.22
[React] nanoid 나노아이디  (0) 2022.05.21
[React] react-scroll-motion 사용하기  (0) 2022.05.04

댓글