In my React/Typescript application, I want to conditionally display a color depending if the value of payload[1]
is null or not. As seen below, I have the style
tag inline.
<li className="recharts-tooltip-item" style={{ payload[1] ? color : `${payload[1].color}` }}>
{payload[0] ? `${payload[1].dataKey} : ${payload[1].value}` : ""}
</li>
I have tried following suggestions from, A better way to change the background color using a ternary operator, but I am getting error: Type '{ payload: Payload<ValueType, NameType>[]; 1: any; }' is not assignable to type 'Properties<string | number, string & {}>'. Object literal may only specify known properties, and 'payload' does not exist in type 'Properties<string | number, string & {}>'
Update of Code:
const CustomTooltip = ({ active, payload, label}: TooltipProps<ValueType, NameType>) => {
if(active && payload && payload.length){
return (
<div className = "custom-tooltip">
<ul className="recharts-tooltip-item-list" style={{padding: '0px', margin: '0px', listStyle:'none'}}>
<li className="recharts-tooltip-item" style={{ color: payload[0] ? color : `${payload[0].color}`}} >
{payload[0] ? `${payload[0].dataKey} : ${payload[0].value}` : ""}
</li>
</ul>
</div>
);
}
return null;
}
CodePudding user response:
You haven't defined a property in the style
prop properly. You're using the raw color value in the falsy situation. I'm pretty sure this is what you're looking for
<li style={{
color: payload[1] ? color : `${payload[1].color}`
}}>
{payload[0] ? `${payload[1].dataKey} : ${payload[1].value}` : ""}
</li >
For your second problem, Make your own type definition for your component. Something along the lines of this should work
type CustomTooltipProps = Omit<TooltipProps<ValueType, NameType>, 'payload'> & {
payload: {
dataKey: any;
value: any;
color: any;
}[]
}
CodePudding user response:
<li className="recharts-tooltip-item"style={{ color: payload[1] ? "red" : `${payload[1].color}` }}>
Can you try to write the code like this?