Reputation: 211
I want to pass the parameter value in style for calculate my width. my code is
function getValue(value) {
if (value === 12) {
return {
width: '( 20 - value )%',
};
}
return false;
}
but the width does not working. I am new to react. please help.
Upvotes: 0
Views: 215
Reputation: 33984
You need something like below. You are checking a constant value, so no need to do the arithmetic, just return 8. You can simplify the function as like below
function getValue(value) {
// return object for style or undefined for no styling
return value === 12 ? {'width': '8% !important' } : undefined;
}
If you were to keep the arithmetic because you wanted to just always do a calculation (for instance). Then a nicer way to write out the function would be like this.
function getValue(value) {
return { 'width': `${20 - value}% !important` };
}
Upvotes: 2
Reputation: 319
You can't calculate if it's a string. Quote marks (''
) make it a string. Also, %
is a remainder operator. It gets the remainder of two numbers. It's similar to division. You can read more about the remainder operator on MDN
I don't understand what this has to do with react, this is more just vanilla javascript.
I think what you may want is
function getValue(value) {
if (value !== 12) { return false; }
return {
width: (20 - value)/100,
};
}
You could also do the following since it only returns if the value if 12
var getValue = value => value === 12 ? { width: 0.08 } : false
This solution uses arrow functions, auto return, and ternary operators. You can read about them on mdn
Upvotes: 2