it-source

React-Router와의 액티브링크

criticalcode 2023. 3. 17. 21:40
반응형

React-Router와의 액티브링크

React-Router(v4)를 테스트하고 있는데 Nav에서 다음 중 하나를 실행하는 데 문제가 있습니다.Linkactive. 다음 중 하나를 클릭하면Link태그를 붙이면 액티브한 것이 동작하기 시작합니다.하지만, 나는 집에 가고 싶다.Link앱이 시작되자마자 활성화되는 것은 앱이 로딩되는 컴포넌트이기 때문입니다./경로요. 방법이 없을까요?

현재 코드는 다음과 같습니다.

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

이것은 React Router v4에 대한 오래된 답변입니다.


<Link>더 이상 가지고 있지 않다activeClassName또는activeStyle특성.react-router v4에서 조건부 스타일링을 하려면 다음을 사용해야 합니다.

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

나는 집에 정확한 재산을 추가했다.<NavLink>이 링크가 없으면 홈링크는 항상 활성화 되어 있을 것입니다./일치할 것이다/about기타 페이지도 참조해 주세요.

리액트 라우터 v6:

출처: React Router를 사용한 Active NavLink 클래스

이제 를 사용할 수 있습니다.className현재 함수를 받아들여 통과시키는 특성isActive다음과 같은 부울 속성:

<NavLink
  to="users"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Users
</NavLink>

v6이 출시되었기 때문에 여러 클래스를 추가할 수도 있습니다.

<NavLink
  to="users"
  className={({ isActive }) =>
    isActive ? 'bg-green-500 font-bold' : 'bg-red-500 font-thin'
  }
>
  Users
</NavLink>

라이브 데모:리액트 라우터를 사용한 액티브 NavLink 클래스

import { NavLink, useMatch, useResolvedPath } from 'react-router-dom';

const CustomNavLink = ({ to, title }) => {
   let resolved = useResolvedPath(to);
   let match = useMatch({ path: resolved.pathname, end: true });

   return (
      <NavLink to={to} className={`d-flex align-items-center py-2 px-4 ${match ? 'cta-btn' : 'c-n-b-link'}`} >
        <span className='ms-1 f-w-600'>{title}</span>
      </NavLink>
)
}

위해서React router V6위의 커스텀 컴포넌트는 경로가 지정된 경로와 일치할 때마다 활성화될 수 있는 네비게이션링크를 반환합니다.to경로.

react-router-dom Version 5.3.0액티브 링크를 유효하게 하기 위해서, 다음의 항목을 사용하고 있습니다.

클래스:

active: {
        // background: 'linear-gradient(180deg, #008b32 0%, #cddc39 100%)',
        // backgroundColor: 'slategray',
        borderBottom: '1px solid white',
        borderRadius: '6px',
        boxShadow: 'rgba(6, 24, 44, 0.4) 0px 0px 0px 2px , rgba(6, 24, 44, 0.65) 0px 4px 6px -1px , rgba(255, 255, 255, 0.08) 0px 1px 0px inset',
        color: 'white',
        fontSize: '14px',
        listStyle: 'none',
        marginLeft: '16px',
        padding: '5px',
        textDecoration: 'none',
        textTransform: 'uppercase',
        transition: 'all 0.1s cubic-bezier(0.42, 0.02, 0.06, 0.05) 0.1s',
    },
    link: {
        '&:hover': {
            borderBottom: '1px solid white',
            borderRadius: '6px',
            boxShadow: 'rgba(6, 24, 44, 0.4) 0px 0px 0px 2px , rgba(6, 24, 44, 0.65) 0px 4px 6px -1px , rgba(255, 255, 255, 0.08) 0px 1px 0px inset',
            color: 'white',
            padding: '5px',
            transition: 'all 0.1s cubic-bezier(0.42, 0.02, 0.06, 0.05) 0.1s',
        },
        color: '#ddf1f9',
        fontSize: '14px',
        listStyle: 'none',
        marginLeft: '16px',
        textDecoration: 'none',
        textTransform: 'uppercase'
    },

NavLink.js

import React from "react";
import { useLocation } from "react-router-dom";


const NavLinks = classes => {
    const pathname = useLocation().pathname
    return (
        <nav>
            <ul className={classes.navlinks}>
                <li>
                    <Link
                        className={`${pathname === '/' ? classes.active : classes.link}`}
                        to='/'
                    >
                        Login
                    </Link>
                </li>
                <li>
                    <Link
                        className={`${pathname === '/dashboard' ? classes.active : classes.link}`}
                        to='/dashboard'
                    >
                        Dashboard
                    </Link>
                </li>
            </ul>
        </nav>
    )
}

@Nick의 답변(React Router v6)과 더불어 상위 컨텍스트에서 액티브한 네비게이션 상태를 필요로 하는 사용자를 위한 것입니다.

조건부 렌더링은 필요에 따라 사용할 수 있습니다.예: 활성화되어 있으면 채워진 아이콘을 렌더링합니다. 그렇지 않으면 일반 아이콘을 렌더링합니다.

현재 진행 중인 경로를 찾아 조건부 렌더링 작업을 할 수 있지만 조금 번거롭습니다.

대신 상태를 수정하는 함수를 작성할 수 있습니다.Navlink님의 스타일 프로포트는 다음과 같습니다.

  const [active, setActive] = useState('home')

  const activate = (isActive, path, activeStyle, nonActiveStyle) => {
    if (isActive) {
      setActive(path)
      return activeStyle
    }
    return nonActiveStyle
  }

  return (
    <nav>
      <NavLink
        to="/"
        style={(activeNav) => activate(activeNav.isActive, 'home')}
      >
        {active === 'home' ? <HomeFill /> : <Home />}
      </NavLink>
      <NavLink
        to="/profile"
        style={(activeNav) => activate(activeNav.isActive, 'profile')}
      >
        {active === 'profile' ? <ProfileFilled /> : <Profile />}
      </NavLink>
    </nav>
  )

저 같은 경우에는<NavLink />자동적으로 설정되다active항목별로 분류하기 때문에 다음 방법을 사용합니다.

my Componet.js

<ListItem component={NavLink} to="/somewhere" className="myactive" > something </ListItem>

myStyle.css

a.active.myactive {
 // some styles
}

v6에서는 @Live Software Developer에서 영감을 받아 이 작업을 수행하는 것이 훨씬 간단하다고 생각합니다(아래 입력은 TypeScript에서 가져옵니다).

const CustomNavLink: React.FC<{ to: string; text: string }> = ({
  to,
  text,
}) => {
  return (
    <NavLink
      to={to}
      className={({ isActive }) => (isActive ? "active" : "inactive")}
    >
      {text}
    </NavLink>
  );
};

언급URL : https://stackoverflow.com/questions/41131450/active-link-with-react-router

반응형