iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

從零開始學習React 系列 第 23

Day23 create React Navigation

  • 分享至 

  • xImage
  •  

昨天己經安裝了react-router-dom,在index.js頁面中導入 BrowserRouter,在App.js頁面中導入Route 和 Switch並完成了React Router path component設定,今天將繼續介紹創建一個簡單的 React 導航欄Navigation。

1.建立一個Navbar.js,導入{NavLink} react-router-dom

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

2.在HTML中如要建立Navigation中的各頁面連結是用<a href="#home">home </a>標籤,在React中建立頁面連結用< NavLink to =” ”>,首頁一樣加上exact。

<NavLink exact to="/"> home </NavLink>

3.最後再把Navbar模組加到App.js中。

Navbar.js

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


const Navbar = () => {
    return (
        <div>
          <div className="header-2">
          <div id="menu-bar" class="fas fa-bars"></div>
          <nav className="navbar">
              <NavLink exact to="/"> home </NavLink>
              <NavLink to="/About US"> About US </NavLink>
              <NavLink to="/product"> product </NavLink>
              <NavLink to="/Services"> Services </NavLink>
              <NavLink to="/contact"> contact </NavLink>
          </nav>

          <div className="icons">
              <i class="fas fa-shopping-cart"></i>     
              <i class="fas fa-user-circle"></i>
              <i class="fas fa-map-marker-alt"></i>
          </div>

          </div>  
        </div>
    )
}

export default Navbar;

App.js

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Product from './Product';
import Services from './Services';
import Contact from './Contact';
import Error from './Error';
import Navbar from './Navbar';


const App = () => {
  
  }
  return (
    <div>    
       <Navbar />
       <Switch>       
         <Route exact path="/" component = {Home} />
         <Route  path="/about" component = {About} />
         <Route  path="/product" component = {Product} />
         <Route  path="/Services" component = {Services} />
         <Route  path="/contact" component = {Contact} />         
         <Route  component = {Error} />
       </Switch>      
    </div>
  )
}

export default App;

https://ithelp.ithome.com.tw/upload/images/20211008/20139800pvCBC3mVFC.png


上一篇
Day22 React-Router
下一篇
Day24 Create Image Gallery in React
系列文
從零開始學習React 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言