Format URL lan Routing ing React- Pandhuan kanggo Nggunakake React Router

Ing aplikasi React, format URL lan routing nduwe peran penting kanggo navigasi kaca lan nampilake konten sing cocog. Kanggo ngatur routing ing React, kita bisa nggunakake perpustakaan. Iki minangka pandhuan dhasar babagan cara nggunakake format URL lan nangani ing aplikasi React. React Router React Router routing

 

Instal React Router

Bukak direktori proyek sampeyan ing terminal lan jalanake printah ing ngisor iki kanggo nginstal: React Router npm install react-router-dom

Impor komponen sing dibutuhake saka menyang komponen React. React Router

 

Nemtokake Rute

Gunakake komponen kanggo mbungkus aplikasi React lan nyetel format URL dhasar. <BrowserRouter>

Gunakake <Route> komponen kanggo nemtokake rute ing aplikasi sampeyan.

Tuladha:

import { BrowserRouter, Route } from 'react-router-dom';  
  
function App() {  
  return( 
    <BrowserRouter>  
      <Route exact path="/" component={Home} />  
      <Route path="/about" component={About} />  
      <Route path="/products" component={Products} />  
    </BrowserRouter>  
 );  
}  

 

Nemtokake Link s

Gunakake komponen kanggo nggawe navigasi ing aplikasi sampeyan. <Link> link

Tuladha:

import { Link } from 'react-router-dom';  
  
function Navigation() {  
  return( 
    <nav>  
      <ul>  
        <li>  
          <Link to="/">Home</Link>  
        </li>  
        <li>  
          <Link to="/about">About</Link>  
        </li>  
        <li>  
          <Link to="/products">Products</Link>  
        </li>  
      </ul>  
    </nav>  
 );  
}  

 

Parameter Jalur Akses

Gunakake <Route> komponen kanthi path atribut ing format /users/:id kanggo ngakses paramèter path.

Ing komponèn ditetepake dening <Route>, sampeyan bisa nggunakake useParams() kanggo ngakses nilai paramèter path.

Tuladha:

import { useParams } from 'react-router-dom';  
  
function User() {  
  const { id } = useParams();  
  
  return <div>User ID: {id}</div>;  
}  

 

Gunakake Switch lan Redirect

Gunakake komponèn kanggo mung nerjemahake rute pisanan sing cocog path. <Switch>

Gunakake komponen kanggo pangguna saka siji path tartamtu menyang liyane. <Redirect> redirect

Tuladha:

import { Switch, Route, Redirect } from 'react-router-dom';  
  
function App() {  
  return( 
    <BrowserRouter>  
      <Switch>  
        <Route exact path="/" component={Home} />  
        <Route path="/about" component={About} />  
        <Route path="/products" component={Products} />  
        <Redirect to="/" />  
      </Switch>  
    </BrowserRouter>  
 );  
}  

 

Iki minangka sawetara konsep dhasar babagan format URL lan routing ing React nggunakake. Kanthi nggunakake, sampeyan bisa nggawe aplikasi React sing fleksibel kanthi kemampuan kanggo navigasi lan nampilake macem-macem konten adhedhasar URL. React Router React Router