React Router DOM
Pada pembahasan router kita akan menggunakan library react-router-dom
, langsung saja install pada proyek dengan perintah berikut.
npm i react-router-dom
Setelah diinstall kita ubah file App.js
agar mengeload file yang akan kita buat dengan nama RoterApp.js
, dan tambahkan file pages/Home.js
untuk halaman home dan pages/About.js
untuk halaman about, sehingga kodenya seperti berikut.
File App.js
import React from "react";
import "./App.css";
import RouterApp from "./RouterApp";
function App() {
return <RouterApp />;
}
export default App;
File RouterApp.js
import React, { Component, Fragment } from "react";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
class RouterApp extends Component {
render() {
return (
<BrowserRouter>
<Fragment>
<nav>
<li>
{" "}
<Link to="/"> Home </Link>{" "}
</li>
<li>
{" "}
<Link to="/about"> About </Link>{" "}
</li>
</nav>
<main>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
</Switch>
</main>
</Fragment>
</BrowserRouter>
);
}
}
export default RouterApp;
File page/Home.js
import React from "react";
const Home = (props) => {
return (
<div>
<h1>Ini Halaman Home</h1>
</div>
);
};
export default Home;
File page/About.js
import React from "react";
const About = (props) => {
return (
<div>
<h1>Ini Halaman About</h1>
</div>
);
};
export default About;
Uji Router
Sehingga hasilnya akan seperti berikut.
Dan tambahkan css pada App.css, seperti berikut.
* {
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
body {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
min-height: 100vh;
}
body nav {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: end;
-ms-flex-pack: end;
justify-content: flex-end;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
background: green;
width: 100%;
height: 40px;
}
body nav li {
margin-right: 2rem;
}
body nav li a {
color: white;
}
body nav li a:hover {
color: yellow;
}
body main {
padding: 3rem;
color: gray;
}
Hasilnya akan seperti berikut.