A cikin aikace-aikacen React, tsara URL da routing taka muhimmiyar rawa wajen kewaya shafuka da nuna abun ciki daidai. Don sarrafa routing cikin React, za mu iya amfani da ɗakin karatu. Anan shine jagorar asali akan yadda ake amfani da su don tsara URLs da sarrafa cikin aikace-aikacen React ɗinku. React Router React Router routing
Shigar React Router
Bude directory ɗin aikin ku a cikin tashar kuma gudanar da umarni mai zuwa don shigar: React Router npm install react-router-dom
Shigo abubuwan da ake buƙata daga cikin sashin React ɗin ku. React Router
Ƙayyade Hanyoyi
Yi amfani da ɓangaren don kunsa aikace-aikacen React ɗin ku kuma saita tsarin URL na tushe. <BrowserRouter>
Yi amfani da <Route>
ɓangaren don ayyana hanyoyi a cikin aikace-aikacen ku.
Misali:
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>
);
}
Bayyana Link s
Yi amfani da ɓangaren don ƙirƙirar kewayawa s a cikin aikace-aikacen ku. <Link>
link
Misali:
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>
);
}
Matsalolin Shiga Hanya
Yi amfani da <Route>
sashi tare da path
sifa a cikin tsari /users/:id
don samun damar sigogin hanya.
A cikin ɓangaren da aka ayyana ta <Route>
, zaku iya amfani da useParams()
don samun damar ƙimar sigogin hanya.
Misali:
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <div>User ID: {id}</div>;
}
Amfani Switch da kuma Redirect
Yi amfani da bangaren don sanya hanyar farko da ta dace da hanyar kawai. <Switch>
Yi amfani da ɓangaren ga masu amfani daga ƙayyadadden hanya zuwa wata. <Redirect>
redirect
Misali:
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>
);
}
Waɗannan wasu mahimman ra'ayoyi ne na tsara URL kuma routing a cikin React ta amfani da. Ta amfani da, zaku iya ƙirƙirar aikace-aikacen React masu sassauƙa tare da ikon kewayawa da nuna abun ciki daban-daban dangane da URL. React Router React Router