I have a question related to tailwindcss and React. I have a property that if a <NavItem />
is focused then the background and the text will change. <LanguageSwitcher />
is another component, and if it is focused, I want it to not change focus state of other items in navbar. <LanguageSwitcher />
doesn't affect URL.
Here's my code for item in navigation bar and images of how <LanguageSwitcher />
affects focus state of other items:
import React from "react";
import { Link } from "react-router-dom";
interface Props {
title: string;
url: string;
icon: JSX.Element;
}
const NavItem: React.FC<Props> = ({ title, url, icon }) => {
//https://tailwindcss.com/docs/hover-focus-and-other-states#pseudo-classes
return (
<Link
to={url}
className="text-center items-center flex-col justify-center font-medium px-1 text-white capitalize hover:font-semibold select-none group"
>
<div className="flex items-center justify-center mb-1 rounded-3xl px-2 py-1 group-hover:bg-btnHover group-focus:bg-btnActive group-focus:text-textActive transition-colors duration-75">
{icon}
</div>
<span>{title}</span>
</Link>
);
};
export default NavItem;
Is it possible? If so, how can I do it, maybe with useLocation
from react-router-dom
or directly with tailwindcss?
"Focus" generally means the UI element the user can currently interact with. I think you are conflating "focus state" with "active state". I'm guessing you want the Link
to remain "active" while other UI elements have, or might not have, "focus", and are being interacted with. Switch to using the NavLink
component and conditionally apply the "active" state CSS classname.
Here's an example * :
import React from "react";
import { NavLink } from "react-router-dom";
interface Props {
title: string;
url: string;
icon: JSX.Element;
}
const NavItem: React.FC<Props> = ({ title, url, icon }) => {
//https://tailwindcss.com/docs/hover-focus-and-other-states#pseudo-classes
return (
<NavLink
to={url}
className="text-center items-center flex-col justify-center font-medium px-1 text-white capitalize hover:font-semibold select-none group"
>
{({ isActive }: { isActive: boolean }) => (
<>
<div
className={
[
"flex items-center justify-center mb-1 rounded-3xl px-2 py-1 group-hover:bg-btnHover transition-colors duration-75"
isActive ? "group-focus:bg-btnActive group-focus:text-textActive" : null
]
.filter(Boolean)
.join(" ")
}
>
{icon}
</div>
<span>{title}</span>
</>
)}
</NavLink>
);
};
export default NavItem;
*Note: I've just guessed/plucked the CSS classnames that looked like they were related to the "focus/active" CSS styling, you will want to double-check the actual classes in your implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.