is there a way to improve my code (Very Important
, Important
, Medium
, Low
, Good
, Excellent
,...
) :
{
Header: "Opinion",
accessor: (row) => row.opinion,
Cell: props =>
<span>
{props.value === "Very important" ?
<span className="text-black">
{props.value}
</span>
: props.value === "Important" ?
: .... //other conditions
}
</span>
},
CodePudding user response:
You might be able to do something like this, which looks a bit cleaner in my opinion!
{"Very Important": <span className="text-black">{props.value}</span>,
"Important": ...,
"Medium": ...,
...
}[props.value]
CodePudding user response:
Well, I think that this depends also on the number of conditions.
If they are 1-2, I might render the JSX directly in the ternary.
If they are more, I'd say that you either use partial renderers (extracting the JSX in separate components) or if there many, as @amit-maraj said, using an inline-switch might be a good variant to avoid too much nesting, even though it's a syntax that it's not that often used (since you don't have to do this kind of stuff).
Additionally, I would extract the JSX rendered from the inline-switch in separate functions, especially if the have logic or they have a large size, in order to keep the file readable.
If this example represents only a way of coloring the text, it might be helpful to have a small component that assigns the class based on the prop value.
eg:
const renderOpinion = (value) => {
const getColor = () => {
switch(value){
case "Very Important":
return "text-black"
//...other cases
default: break;
}
}
return <span className={getColor()}>{value}</span>
}
And of course, if they have base classes, using something like classnames or doing directly like:
className={`text-small ${getColor()}`}
and then just call it as :
//...
Cell: props => renderOpinion(props.value)