i want to display text based on condition in a reusable component using react and javascript.
what i am trying to do?
I have a reusable component Bar like below,
const Bar = ({
label,
indeterminate,
showValue = !indeterminate,
value,
max = 100,
...rest
}: BarProps) => (
<BarWrapper {...rest}>
<Wrapper>
<Progress
value={value}
max={max}
/>
{indeterminate && <span />}
{showValue && (
<span>
{value} <Unit>%</Unit>
</span>
)}
</Wrapper>
{label && <Label>{label}</Label>}
</BarWrapper>
);
I use this Bar component in couple of other components.
now there is a component "ParentComponent" that uses this Bar component. but in here it doesnt want to show value with %. instead it wants to show limit/total value. so i had added code like so,
const ParentComponent = () => {
const limit = "10";
const total= "15";
return(
<Bar
showCompleted
limit={limit}
total={total}
/>
);
}
And i have modified Bar component to display limit/total instead of showing percentage value.
const Bar = ({
label,
indeterminate,
showCompleted = !indeterminate,
limit,
total,
showValue = !indeterminate,
value,
max = 100,
...rest
}: BarProps) => (
<BarWrapper {...rest}>
<Wrapper>
<Progress
value={value}
max={max}
/>
{indeterminate && <span />}
{showValue && (
<span>
{value} <Unit>%</Unit>
</span>
)}
{showCompleted && (
<span>{limit}/{total}
</Wrapper>
{label && <Label>{label}</Label>}
</BarWrapper>
);
But the above code shows both percentage value and limit/total. how can i fix this. could someone help me with this. thanks.
CodePudding user response:
You can do the following (two versions to account for the additional condition. Not sure I understand the logic you're trying to achieve but you can modify the flags appropriately). That's the solution if you would have either value
or completed value
(can't be both at the same time - which I think is you're trying to achieve).
That way you don't need 2 flags (showValue
, showCompletedValue
) - Just one. If showCompletedValue prop is passed it displays the first one (limit/total). If it's omitted, it'll display the second one (unit %).
{showCompletedValue ? (
<span>{limit}/{total}</span>
) : (
<span>{value} <Unit>%</Unit></span>
)}
// Another option if you need to combine 2 flags
{(showCompletedValue && !indeterminate) ? (
<span>{limit}/{total}</span>
) : (
<span>{value} <Unit>%</Unit></span>
)}
The second example is in case it has to meet both conditions.
CodePudding user response:
Try with showCompletedValue
prop:
const ParentComponent = () => {
const limit = "10";
const total= "15";
return(
<Bar
showCompletedValue <--- update this prop.
limit={limit}
total={total}
/>
);
}