front-end/React
[React] 천단위마다 쉼표 넣는 방법
-제이리
2022. 5. 23. 19:47
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