Reputation: 741
I want to increase padding value using its previous value, something like this:
const newListItemStyle = {
...listItemStyle,
paddingRight: listItemStyle.paddingRight + '50px',
}
How can i do something like this ?
Upvotes: 0
Views: 287
Reputation: 4639
Adiga's answer will help you with simple operations like '50px' + '50px'
, but for a more bulletproof answer that will take into effect varying units (or even no units) and allow for decimal places, you would be better off avoiding parseInt
.
Instead you can use a regular expression that will match numbers and possibly a decimal point and then convert that to a number using the Number()
function, which won't round it like parseInt()
would.
The logic of determining how much extra padding to add and what the unit on that should be I leave to you.
const newListItemStyle = {
...listItemStyle,
paddingRight: Number(listItemStyle.paddingRight.match(/[\d\.]+/g)) + 50 + 'px'
}
Upvotes: 1
Reputation: 35261
You can use parseInt
to get the number part first. Then add 50
to get the sum. Then add "px"
to convert it to a string
const newListItemStyle = {
...listItemStyle,
paddingRight: parseInt(listItemStyle.paddingRight) + 50 + 'px'
}
Upvotes: 1