Coder Social home page Coder Social logo

thiagozanetti / react-intl-currency-input Goto Github PK

View Code? Open in Web Editor NEW
196.0 5.0 48.0 1.52 MB

React component for i18n currency input using Intl API.

Home Page: https://react-intl-currency-input-app.vercel.app

License: MIT License

HTML 2.02% CSS 2.74% TypeScript 89.36% JavaScript 5.89%
intl-api react intl react18 typescript vite

react-intl-currency-input's Introduction

react-intl-currency-input

A React component for i18n currency input using Intl API.

Installation

$ npm install react-intl-currency-input --save-dev

How to use

import React from "react"
import IntlCurrencyInput from "react-intl-currency-input"

const currencyConfig = {
  locale: "pt-BR",
  formats: {
    number: {
      BRL: {
        style: "currency",
        currency: "BRL",
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      },
    },
  },
};

const BrlCurrencyComponent = () => {
  const handleChange = (event, value, maskedValue) => {
    event.preventDefault();

    console.log(value); // value without mask (ex: 1234.56)
    console.log(maskedValue); // masked value (ex: R$1234,56)
  };

  return(
    <IntlCurrencyInput currency="BRL" config={currencyConfig}
            onChange={handleChange} />
  );
}

export default BrlCurrencyComponent;

Example

example

To run the example:

$ npx turbo run start:app

And a new browser window will open at http://localhost:3000

Properties

Name Type Default Description
defaultValue number 0 Sets the default / initial value to be used by the component on the first load
currency string USD Sets the currency code
config object USD related configuration Configuration object compliant with react-intl intlShape
autoFocus boolean false Enables auto-focus when the component gets displayed
autoSelect boolean false Enables auto-select when the component gets displayed
autoReset boolean false Resets component's internal state when loses focus
onChange function undefined (event, value, maskedValued) => {}

Exposes the Event itself, the value with no mask and maskedValue for displaying purposes
onFocus function undefined (event, value, maskedValued) => {

Called when the component gains focus
onBlur function undefined (event, value, maskedValued) => {

Called when the component loses focus
onKeyPress function undefined (event, key, keyCode) => {}

Called when a key is pressed
max number undefined Maximum value for the input. Input does not change if the value is greater than max

All the other undocumented properties available for any React Component should also be available.

react-intl-currency-input's People

Contributors

andrewfluck avatar armanio avatar bernardofbbraga avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar felipemouradev avatar felps-dev avatar gabteles avatar ifeins avatar kewers avatar thiagozanetti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-intl-currency-input's Issues

Problema com NextJS em produção

Estou utilizando NextJS em minha aplicação estou tendo erro ao carregar a página utilizando SSR.
Quando acesso a página e dou refresh está quebrando apontando erro 500. Depois de muito buscar o porque vi que o problema está no uso desse pacote.
Rodando a aplicação local ou realizando build local, tudo funciona perfeitamente.
Alguém já teve esse problema? Alguma ideia do que pode estar acontecendo?

Problema no Plataforma IOS Mobile

Ao tentar utilizar o componente no iphone, ele está perdendo o focus e levando a pagina para o topo, esse problema é algo conhecido ou não?

Version: "react-intl-currency-input": "^0.2.6"

Suporte ao Typescript

Olá

Gostaria de saber se já foi implementado suporte ao typescript. Se sim, teria alguns exemplos de uso?

Carregar o input com valor pré definido

Boa tarde!

Está funcionando corretamente quando o valor inicia zerado, mas ao carregar da minha API para alteraçao do campo, o valor é carregado sem as decimais. Como resolver?

Exemplo: 500,00 será salvo no banco 500

Ao carregar o valor para o input é apresentado

R$ 5,00

Código:

import IntlCurrencyInput from "react-intl-currency-input"

const currencyConfig = {
  locale: "pt-BR",
  formats: {
    number: {
      BRL: {
        style: "currency",
        currency: "BRL",
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      },
    },
  },
};

function NumberFormatCustom(props) {
   const {inputRef, onChange, ...other} = props

   return (
      <IntlCurrencyInput 
      {...other } 
      currency="BRL" 
      config={currencyConfig}
      onChange={(e, value) => {
         onChange({
            target: {
               name: props.name,
               value: value
            }
         })
      }}
      />
   )

NumberFormatCustom.propTypes = {
   inputRef: PropTypes.func.isRequired,
   name: PropTypes.string.isRequired,
   onChange: PropTypes.func.isRequired,
};


export default function TextFieldMonetario (props) {
    return <TextField
            variant="outlined" 
            margin="normal" 
            InputProps={{
               inputComponent: NumberFormatCustom,
             }}
            {...props} />
}  

bump deps to latest

any plans on making this lib up to the latest version of dependencies? (including node v20)

i'm relying on a specific scenario with this deps on my work.

Can't input amount when currency is set to JPY

When I try to type an amount it stays on 0.

This is how my code looks like:

this.currencyConfig = {
  locale: 'en-US',
  formats: {
    number: {
      JPY: {
        style: 'currency',
        currency: 'JPY'
      }
    }
  }
}

<IntlCurrencyInput currency={'JPY'} config={this.currencyConfig}/>

The same codes works well for USD and EUR.
I think that the difference is that in JPY there is no concept of subunits (no cents) and so the input doesn't handle it well.

Incorrect mask for nonzero value.

The mask is incorrect when the initial value is different from 0.

image

image

This bug occur when de default value isn't 0. Independent of the type and size

Solution:
image

BUG? Possibility to type negative numbers

Hello, i don't know if this is a bug...

I know i can press "minus" before prepend currency to make the value negative, but when i need transform an already typed value to negative and press "minus" the value and the mask return to 0.

Will be cool if i can press "minus" and the input toggle between positive and negative values automatically.

Thanks!!

Problema no NextJs

Estou utilizando NextJS em minha aplicação estou tendo erro ao carregar a página.
O erro esta no print abaixo:

Captura de tela de 2022-09-19 16-31-39

Algum coisa que posso fazer?

Cannot resolve dependency 'big.js'

Adicionado via yarn surge o erro:

node_modules\react-intl-currency-input\dist\format-currency.js:8:19: Cannot resolve dependency 'big.js'
6 | exports.default = formatCurrency;
7 |

8 | var _big = require("big.js");
| ^
9 |
10 | var _big2 = _interopRequireDefault(_big);
11 |

Max Value Not Working

Hey everyone, i have a problem when i'm set max value the component doesn't work.

See that:

    <Form.Item name="taxa" rules={[{ required: true, message: 'Campo obrigatório !' }, { max: 100, message: 'O maximo de percentual é 100' }]}>
          <StInputMasked max={100} defaultValue={fee} currency="BRL" config={currencyFinancial} onKeyPressCapture={handleTaxa} onChange={handleChange} />
    </Form.Item>

image

Version: "react-intl-currency-input": "^0.2.6",

Contains an input of type undefined with both value and defaultValue props

When i pass the defaultValue prop to set a value to the input i get this warning in the console:

warning.js?8a56:36 Warning: IntlCurrencyInput contains an input of type undefined 
with both value and defaultValue props. 
Input elements must be either controlled or uncontrolled (specify either the value prop, 
or the defaultValue prop, but not both).

Como iniciar o input vazio?

Boa noite,

gostaria de saber como iniciar o input vazio, pois atualmente, por padrão ele é iniciado como R$0,00. Alguém poderia me ajudar?

Currency symbol doesn't change when currency property is changed

Hi,

I have an AmountField component in my project for inputting money amounts which leverages IntlCurrencyInput and is defined like so:

class AmountField extends Component {

    getCurrencyConfig(currency) {
        let currencyConfig = {
            locale: 'en-US',
            formats: {
                number: {

                }
            }
        }

        currencyConfig['formats']['number'][currency] = {style: 'currency', currency: currency}
        return currencyConfig
    }

    render() {
        return (
            <div className='amount-field'>
                <label>Amount</label>
                <IntlCurrencyInput currency={this.props.currency} 
                    config={this.getCurrencyConfig(this.props.currency)}
                    onChange={(event, value, maskedValue) => this.props.onAmountChanged(value)}/>
                    <div>
                        <hr/>
                    </div>
            </div>
        )
    }
}

The AmountField component is used like so:
<AmountField currency={this.state.amountCurrency}/>

I want to enable the user to change the currency (using a separate dropdown), but the problem is when I call this.setState({amountCurrency: "EUR"}) then the symbol in the intl-currency-input remains the same. Only when I re-focus on the intl-currency-input then the currency symbol changes.

I've debugged this and the AmountField does get the new currency input upon change and passes it to the IntlCurrencyInput but there it seems that the change doesn't happen.

Atualizei pra ultima versão 0.2.4 e agora ele não está respeitando o minimo de caracteres depois da , quando vai pra edição

Olá tudo bem?

Precisei atualizar o componente pra a versão 2.4 e ele não tem funcionado muito bem, quando estou usando sem centavos funciona normal ex: 20 reais quando vai pra edição aparece os 20, mas se eu salvar 20,50 na hora de mostrar ele está mostrando 2,05 verifiquei a documentação e não fala nada de atualizar a forma como passo os parâmetros da configuração acredito que seja um bug mesmo.

Aguardo retorno a respeito, desde já grato pela atenção.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.