Soy nuevo para reaccionar y quiero que mi estilo flotante permanezca activo mientras la página actual está abierta. Necesito hacer una condición pero no sé cómo
const StyledLi = styled.li` `list-style: none; display: flex; &:hover { background-color: rgba(84, 78, 114, 1); border-radius: 10px 0px 0px 10px;//enter code here } background-color: ${props => props.path ? "rgba(84, 78, 114, 1)" : "white"}; border-radius: ${props => props.path ? "0px 0px 0px 10px" : "0px"}; ; const SidebarMenu = () => { const location = useLocation(); let path; const toHandler = (route) => (path = route); return ( <StyledAside> <StyledUl> <StyledLi> <NavLink style={navLinkStyles} to={toHandler("/dashboard/main")}> {location.pathname === path ? <StyledIcon url={homePageYellowIcon}/> : <StyledIcon url={homePageIcon}/>} <span>Главная</span> </NavLink> </StyledLi> ); };
Puede hacer referencia a otros componentes con estilo. Importe el Navlink
y cree un componente con estilo a partir de él para que pueda ser referenciado dentro del componente StyledLi
.
import { NavLink as BaseNavLink } from "react-router-dom"; const NavLink = styled(BaseNavLink)` display: flex; align-items: center; font-size: 18px; color: #fff; font-weight: 700; text-decoration: none; padding: 8px 3px; width: 100%; &.active { color: #f8dc2f; } `;
Ahora también aplique el estilo de desplazamiento cuando el componente NavLink
anidado tenga un nombre de clase "active"
.
const StyledLi = styled.li` list-style: none; display: flex; &:hover, ${NavLink}.active { background-color: rgba(84, 78, 114, 1); border-radius: 10px 0px 0px 10px; } background-color: ${(props) => props.path ? "rgba(84, 78, 114, 1)" : "white"}; border-radius: ${(props) => (props.path ? "0px 0px 0px 10px" : "0px")}; `;
NavLink
Aquí está lo mismo pero diseñando el NavLink
.
const NavLink = styled(BaseNavLink)` display: flex; align-items: center; font-size: 18px; color: #888; font-weight: 700; text-decoration: none; padding: 8px 3px; width: 100%; &:hover, &.active { background-color: rgba(84, 78, 114, 1); border-radius: 10px 0px 0px 10px; } &.active { color: #f8dc2f; } `; const StyledLi = styled.li` list-style: none; display: flex; background-color: ${(props) => props.path ? "rgba(84, 78, 114, 1)" : "white"}; border-radius: ${(props) => (props.path ? "0px 0px 0px 10px" : "0px")}; `;