Skip to content

Commit af5f1ca

Browse files
committed
basic example: useLocation
1 parent 7f5a23e commit af5f1ca

File tree

3 files changed

+29
-13
lines changed

3 files changed

+29
-13
lines changed

src/App.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import Home from "./Components/Home";
44
import Gallery from "./Components/Gallery";
55
import About from "./Components/About";
66

7-
function App() {
7+
function App() {
88
return (
99
<Fragment>
1010
<Router>

src/Components/Gallery.jsx

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
1-
import React from "react";
1+
import React, { useEffect, useState } from "react";
2+
import { useLocation } from "react-router-dom";
23

3-
const Gallery = () => (
4-
<div>
5-
<h1>Hello, I'm Gallery component</h1>
4+
const Gallery = () => {
5+
const [gallery, setGallery] = useState([]);
6+
const location = useLocation();
7+
useEffect(() => {
8+
console.log(location.pathname);
9+
const searchParams = new URLSearchParams(location.search);
10+
const print = Number(searchParams.getAll("print")[0] || 5);
11+
setGallery(
12+
new Array(print).fill("https://placem.at/things?w=100&h=100&random=")
13+
);
14+
}, [location, setGallery]);
15+
16+
return (
617
<div>
7-
<img src="https://placem.at/things?w=100&h=100&random=0" alt="image0" />
8-
<img src="https://placem.at/things?w=100&h=100&random=1" alt="image1" />
9-
<img src="https://placem.at/things?w=100&h=100&random=2" alt="image2" />
10-
<img src="https://placem.at/things?w=100&h=100&random=3" alt="image3" />
11-
<img src="https://placem.at/things?w=100&h=100&random=4" alt="image4" />
18+
<h1>Hello, I'm Gallery component</h1>
19+
<div>
20+
{gallery.map((v, i) => (
21+
<img src={v + i} alt={v + i} key={i} />
22+
))}
23+
</div>
1224
</div>
13-
</div>
14-
);
25+
);
26+
};
1527

1628
export default Gallery;

src/Components/Home.jsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const Home = () => {
44
const history = useHistory();
55

66
const handleAbout = () => history.push("/about"); //add programmatic routing
7+
const handleGallery = () => history.push("/gallery?print=20"); //add programmatic routing
78
const handleBack = () => history.goBack(); //Back programmatic routing
89
const handleForward = () => history.goForward(); //Forward programmatic routing
910

@@ -12,9 +13,12 @@ const Home = () => {
1213
<h1>Hello, I'm Home component </h1>
1314
<hr />
1415
<h2>useHistory</h2>
15-
<button onClick={handleAbout}>About</button>
16+
<button onClick={handleAbout}>Go to "About"</button>
1617
<button onClick={handleBack}>Back</button>
1718
<button onClick={handleForward}>Forward</button>
19+
<button onClick={handleGallery}>
20+
Go to "Gallery" with params "?print=20"
21+
</button>
1822
<hr />
1923
</div>
2024
);

0 commit comments

Comments
 (0)