Skip to content

Commit

Permalink
fix: Input getting rerendered when value prop changes without manual …
Browse files Browse the repository at this point in the history
…input changes
  • Loading branch information
saschb2b committed Sep 4, 2024
1 parent c9f029f commit e8505f2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
10 changes: 10 additions & 0 deletions lib/components/CurrencyTextField/CurrencyTextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,16 @@ export const CurrencyTextField: React.FC<CurrencyTextFieldProps> = ({
}));
}, [currency, precision]);

/**
* Update the internal value when the value prop changes.
* This is necessary to keep the input value in sync with the value prop.
*/
useEffect(() => {
if (value) {
setInternalValue(value);
}
}, [value]);

/**
* Handle changes to the input value.
*
Expand Down
19 changes: 16 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import * as React from 'react';
import Dinero from 'dinero.js';
import { CurrencyTextField } from '../dist/material-ui-currency-textfield';
import { Typography } from '@mui/material';
import { Box, Button, Typography } from '@mui/material';

export const App: React.FC = () => {
const [brutto, setBrutto] = React.useState<Dinero.Dinero>(
Dinero({ amount: 133742, currency: 'EUR', precision: 2 }),
);

return (
<div>
<Box
sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: 200 }}
>
<CurrencyTextField
label={'Einkommen'}
name={'einkommen'}
Expand All @@ -25,7 +27,18 @@ export const App: React.FC = () => {
setBrutto(value);
}}
/>
<Button
variant="contained"
color="primary"
onClick={() => {
setBrutto((prev) =>
prev.add(Dinero({ amount: 5000, currency: 'EUR' })),
);
}}
>
50 € hinzufügen
</Button>
<Typography>Dinero amount: {brutto.getAmount()}</Typography>
</div>
</Box>
);
};

0 comments on commit e8505f2

Please sign in to comment.