Sh11ntar0 / React

1 stars 0 forks source link

React Router #2

Open TakayasuNasu opened 3 years ago

TakayasuNasu commented 3 years ago

React Router: Declarative Routing for React.js 公式ドキュメント

インストール

npm install --save react-router-dom
yarn add react-router-dom
TakayasuNasu commented 3 years ago

srcディレクトリの直下にpagesディレクトリを作成します。 pagesディレクトリ内にIndex.js ProductDetai.js RegistProduct.jsファイルを作成

src
|--pages
|  |--Index.js
|  |--ProductDetai.js
|  |--RegistProduct.js
TakayasuNasu commented 3 years ago

App.jsを下記に更新

import React from 'react'
import { Reset } from 'styled-reset'
import {
  BrowserRouter as Router,
  Switch,
  Route
} from 'react-router-dom'

import Index from './pages/Index'
import ProductDetai from './pages/ProductDetai'
import RegistProduct from './pages/RegistProduct'

const App = () => {
  return (
    <React.Fragment>
      <Reset />
      <Router>
        <Switch>
          <Route path='/product-detail'>
            <ProductDetai />
          </Route>
          <Route path='/regist-product'>
            <RegistProduct />
          </Route>
          <Route path='/'>
            <Index />
          </Route>
        </Switch>
      </Router>
    </React.Fragment>
  )
}

export default App;
TakayasuNasu commented 3 years ago

pages/Index.js

import { Link } from 'react-router-dom'
import logo from '../logo.svg'
import '../App.css'
import Clock from '../Clock'
import ClockWithUse from '../ClockWithUse'

const Index = props => {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Hello World! <code>src/App.js</code> and save to reload.
        </p>
        <p><Link to='/product-detail'>to product-detail</Link></p>
        <p><Link to='/regist-product'>to regist-product</Link></p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
        <Clock date={new Date()} />
        <ClockWithUse />
      </header>
    </div>
  );
}
export default Index



pages/ProductDetai.js

import React from 'react'
import { Link } from 'react-router-dom'

const ProductDetai = props => {
  return (
    <React.Fragment>
      <h1>ProductDetai</h1>
      <p><Link to='/'>Top</Link></p>
      <p><Link to='/regist-product'>to regist-product</Link></p>
    </React.Fragment>
  )
}

export default ProductDetai



pages/RegistProduct.js

import React from 'react'
import { Link } from 'react-router-dom'

const RegistProduct = props => {
  return (
    <React.Fragment>
      <h1>RegistProduct</h1>
      <p><Link to='/'>Top</Link></p>
      <p><Link to='/product-detail'>to product-detail</Link></p>
    </React.Fragment>
  )
}

export default RegistProduct