React JSėė íėīė§ëĨž ė ííęļ° ėíī React-router-dom
ė ėŽėĐíīėž íëĪ.
$ npm i react-router-dom
routes íīëė components íīëëĨž ë§ëĪėëĪ.
Movie.js íėžė components íīë ėėžëĄ ėŪęēžëĪ.
routes íīë ėė Home.js íėžęģž Detail.js íėžė ë§ëĪėëĪ.
App.js íėžė App ėŧīíŽëíļė ėėąí ė―ëëĨž Home.js íėžė Home ėŧīíŽëíļëĄ ėŪęēžëĪ.
ëė App ėŧīíŽëíļë router(urlė ëģīęģ ėë component)ëĨž render
íëëĄ íëĪ.
urlė ë°ëžė Home ëë Detailė ëģīėŽėĢžęē ëëĪ.
react-router (v6 ėīė) ėŽėĐëē ė°ļęģ
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./routes/Home";
import Detail from "./routes/Detail";
function App() {
return (
<Router>
<Routes> // root ęē―ëĄëĨž ë§Ļ ë§ė§ë§ė ėėąíīėž íëĪ.
<Route path="/movie" element={<Detail />} />
<Route path="/" element={<Home />} />
</Routes>
</Router>
);
}
export default App;
movie titleëĨž íīëĶíëĐī detail íėīė§ëĄ ėīëíëëĄ íęļ° ėíī linkëĨž ėŽėĐíëĪ.
a íę·ļëĨž ėŽėĐí ėë ėė§ë§ ėī ë°ĐëēėžëĄë íėīė§ ė ėēīę° ėŽëĄëĐëëĪ.
link ėŧīíŽëíļ
ë ëļëžė°ė ëĨž ėëĄęģ ėđĻ íė§ ėęģ ë ëĪëĨļ íėīė§ëĄ ėīë
ėėžėĪëĪ.
<h2>
<Link to="/movie">{title}</Link>
</h2>
detail íėīė§ėė ėĪė ëĄ íīëđ ėíė ëí ė ëģīëĪė ëģīėŽėĢžęļ° ėíī urlė íëžëŊļí°(urlė ėí ëģė)ëĨž ėķę°íëĪ.
// App.js
<Route path="/movie/:id" element={<Detail />} />
// Movie.js
const Movie = ({ id, title }) => {
return (
<h2>
<Link to={`/movie/${id}`}>{title}</Link>
</h2>
};
// Detail.js
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
const Detail = () => {
const { id } = useParams(); // ðĄ useParams íĻėëĨž ėīėĐíī urlė íëžëŊļí°ëĨž ë°ėėŽ ė ėëĪ
const [loading, setLoading] = useState(true);
const [movie, setMovie] = useState({});
const getMovie = async () => {
const json = await (
await fetch(`https://yts.mx/api/v2/movie_details.json?movie_id=${id}`)
).json();
setMovie(json.data.movie);
setLoading(false);
};
useEffect(() => getMovie());
return (
<div>
<h1>
{loading ? (
<strong>ëĄëĐ ėĪ...</strong>
) : (
`${movie.title} (rating ${movie.rating})`
)}
</h1>
<img src={movie.large_cover_image} alt={movie.title} />
<p>{movie.description_full}</p>
</div>
);
};
export default Detail;