Router - rkaku/react-hooks-101 GitHub Wiki

react-router@v4を使ってみよう:シンプルなtutorial

yarn add react-router-dom

Route

<BrouserRouter>
<Route path="/" exact component={ Home } />
<Route path="/about" exact component={ About } />
<Route path="/user/:id" exact component={ User } />
function User({ match }) {
  return <h1>ID: { match.params.id }</h1>
}

NavLink

<BrouserRouter>
<NavLink
  className="App-link"
  to="/" exact
  activeClassName="Link-active-style"
>
  Home
</NavLink>

Redirect

<Route
  path="/user/:id" exact
  render={({ match }) => {
    return loggedIn ? (
      <h1>{ match.params.id }</h1>
      // <User match={ match } /> ??
    ) : (
      <Render to="/" />
    )
  }}
/>

Prompt

const [loggedIn, setLoggedIn] = useState(false)
const [name, setName] = useState("")

function onChangeHandle(event) {
  setName(event.target.value)
}
<ul className="ul-style">
<li className="li-style">

<input
  type="text"
  value="name"
  onChange={ onChangeHandle }
/>

<Prompt
  when={ loggedIn && !name }
  message={(location) => {
    return location.pathname.startWith('/user') ? true : "Are you sure?"
  }}
/>
.ul-style {
  display: flex;
  flex-direction: row;
}

.li-style {
  width: 200px;
  list-style-type: none;
  border: 1px solid gray;
  padding: 5px;
}

.button {
  width: 100px;
  padding: 5px;
}
⚠️ **GitHub.com Fallback** ⚠️