Browse Source

Prototype some react-router-dom v5 routing

Andrew Swistak 6 năm trước cách đây
mục cha
commit
0fe9dc9fac

+ 5 - 3
app/javascript/packs/frontend/app.jsx

@@ -17,12 +17,14 @@ class App extends React.Component {
         <ApplicationLayout>
           <Switch>
             <Route exact path="/" component={TestComponent} />
-            <Route exact path="/pokemon" component={Pokemon} />
+            <Route path="/pokemon" component={Pokemon} />
 
-            <Route exact path="/*" component={NotFound} />
+            <Route component={NotFound} />
           </Switch>
 
-          <Link to="/pokemon">some pokemon</Link>
+          <p>
+            <Link to="/pokemon">Show me the pokemon!</Link>
+          </p>
         </ApplicationLayout>
       </BrowserRouter>
     );

+ 9 - 3
app/javascript/packs/frontend/components/pages/pokemon.jsx

@@ -1,13 +1,19 @@
 import React from 'react';
 import {Route, Switch} from 'react-router-dom';
 
-import ShowPokemon from './pokemon/show';
+import PokemonShow from './pokemon/show';
+import PokemonIndex from './pokemon/index';
 
-function Pokemon() {
+import NotFound from './not_found';
+
+function Pokemon({match}) {
   return (
     <>
       <Switch>
-        <Route path="/pokemon" component={ShowPokemon} />
+        <Route exact path={`${match.path}/:id`} component={PokemonShow} />
+        <Route exact path={`${match.path}`} component={PokemonIndex} />
+
+        <Route component={NotFound} />
       </Switch>
     </>
   );

+ 24 - 0
app/javascript/packs/frontend/components/pages/pokemon/index.jsx

@@ -0,0 +1,24 @@
+import React from 'react';
+import {Link} from 'react-router-dom';
+
+import {Pokemon} from '../../../api';
+
+class PokemonIndex extends React.Component {
+  state = {
+    pokemon: [],
+  };
+
+  render() {
+    const pokemon = this.state.pokemon.map((pkmn, i) => {
+      return (
+        <li key={pkmn.id}>
+          <Link to={`/pokemon/${pkmn.id}`}>{pkmn.nickname}</Link>
+        </li>
+      );
+    });
+
+    return <ul>{pokemon}</ul>;
+  }
+}
+
+export default PokemonIndex;