Adding Routing

Install npm routing

Buat file baru di dalam folder component, Customers.jsx, movieForm.jsx, notFound.jsx, Rentals.jsx

Customers.jsx

import React from "react";

const Customers = () => {
    return <h1>Customer</h1>;
};

export default Customers;

movieForm.jsx

import React from "react";

const MovieForm = () => {
    return <h1>MovieForm</h1>;
};

export default MovieForm;

nofFound.jsx

import React from "react";

const NotFound = () => {
    return <h1>NotFound</h1>;
};

export default NotFound;

Rentals.jsx

import React from "react";

const Rentals = () => {
    return <h1>Rentals</h1>;
};

export default Rentals;

Lalu buka file index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.css';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

dan buka file app.js

import { Route, Redirect, Switch } from 'react-router-dom';
import Movies from './components/movies';
import Rentals from './components/Rentals';
import NotFound from './components/notFound';
import Customers from './components/Customers';
import './App.css';

function App() {
  return (
    <main className="container">
      <Switch>
        <Route path="/movies" component={Movies}></Route>
        <Route path="/customers" component={Customers}></Route>
        <Route path="/rentals" component={Rentals}></Route>
        <Route path="/not-found" component={NotFound}></Route>
        <Redirect from="/" exact to="/movies" />
        <Redirect to="not-found" />
      </Switch>
    </main>
  );
}

export default App;

Route path ada penganti href untuk react router dom

exact adalah untuk menspesifikan redirect yg bersangkutan saja

Redirect yg hanya to ketika kita ketik url asal seperti /asdsagfsa dia akan ke not found

Last updated

Was this helpful?