React

JSX 링크로 라우터 이동

youngseokim_kr 2021. 11. 21. 17:15
import { BrowserRouter,Route,Switch } from "react-router-dom";
import About from "./pages/About";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
import NotFound from "./pages/NotFound";
import Links from "./components/Links";






function App() {
  return (
    <BrowserRouter>
    <Links />
      <Switch>
        <Route path="/profile/:id" component={Profile} />
        <Route path="/profile" component={Profile} />
        <Route path="/about"  component={About} />
        <Route path="/" exact component={Home} />
        <Route component={NotFound} />
       </Switch>
    </BrowserRouter>
  );
}

export default App;

app.js

이런 결과가 나오고 링크를 타고 가도 새로고침이 안되고 화면이 바로 나오는걸 확인 할 수 있다.

NavLink

import { NavLink } from 'react-router-dom';

activeClassName, activeStyle 처럼 active 상태에 대한 스타일 지정이 가능하다.

Route 의 path  처럼 동작하기 때문에 exact 가 있다.

import { NavLink } from "react-router-dom";

const activeStyle={color:"yellow"};

export default function NavLinks() {
  return (
    <ul>
      <li>
        <NavLink to="/" exact activeStyle={activeStyle}>
          Home
          </NavLink>
      </li>
      <li>
        <NavLink to="/profile" exact activeStyle={activeStyle}>
          Profile
          </NavLink>
      </li>
      <li>
        <NavLink to="/profile/1" activeStyle={activeStyle}>
          Profile/1
          </NavLink>
      </li>
      <li>
        <NavLink 
        to="/about" 
        activeStyle={activeStyle} 
        isActive={(match, location) => {
          console.log(location);
          return match !== null && location.search==="";
        }}>
          About
          </NavLink>
      </li>
      <li>
        <NavLink to="/about?name=mark" activeStyle={activeStyle}
        isActive={(match,location) => {
          return match !== null && location.search==="?name=mark";
        }}> About?name=mark
          </NavLink>
      </li>
    </ul>
  )
}

'React' 카테고리의 다른 글

controlled component , uncontrolled component  (0) 2021.11.22
JS 로 라우팅 이동하기  (0) 2021.11.21
Switch, NotFound  (0) 2021.11.21
Dynamic 라우팅  (0) 2021.11.21
React 라우팅  (0) 2021.11.21