I am working on creating a Button component in ReactJS that can be styled using props such as primary
, rounded
, and outline
. To apply these styles, I use the className
function from the "classnames" library.
import className from 'classnames'
interface ButtonProps {
children: any // Elements placed within the Button
outline?: boolean // Adds an outline to the Button, removing background color and changing font color
rounded?: boolean // Adds border radius to the Button
primary?: boolean // Sets a blue background color for the Button
[key: string]: any // Additional props like event handlers
}
function Button({
children,
outline,
rounded,
primary,
...rest
}: ButtonProps) {
const classNames =
className(
'flex items-center select-none px-3 py-0.5 border border-2 font-medium',
{
'text-white bg-blue-600 border-blue-600': primary,
'rounded-lg': rounded,
'text-blue-500 bg-transparent': outline && primary,
},
rest.className
)
return (
<button {...rest} className={classNames}>
{children}
</button>
)
}
When I only set the primary
prop, the Button looks like this:
https://i.sstatic.net/NfFc2.jpg
The classnames in the browser inspector show
flex items-center select-none px-3 py-0.5 border border-2 font-medium text-white bg-blue-600 border-blue-600
, which is correct. However, when I add both the outline
and primary
props, the Button appears differently:
https://i.sstatic.net/SIaTC.jpg
The classnames change to
flex items-center select-none px-3 py-0.5 border border-2 font-medium text-white bg-blue-600 border-blue-600 text-blue-500 bg-transparent
As seen, bg-transparent
and text-blue-500
override bg-blue-600
and text-white
. It seems that bg-blue-600
is overridden by bg-transparent
, but text-white
is not overridden by text-blue-500
.
This issue can be observed in the CSS styles section of the Developer tools: https://i.sstatic.net/ImuM7.png
Why does this happen and how can I resolve this problem?
Thank you!