What is a Query Parameter?
A query parameter is a part of the URL that comes after the ? symbol and is used to pass additional data to the server or the frontend application. Query parameters are key-value pairs, separated by the & symbol, and they are used to define specific information needed for the request or to filter content in a web application.
For example, consider the URL
/search?query=keyword
In this case,
1. /search is the path.
2. query=keyword is the query parameter, where query is the key, and keyword is the value.
The application can extract the value from the query parameter to filter or display specific results.
How to access the query parameters?
In React, the useSearchParams hook (from react-router-dom) allows you to access and manipulate query parameters in the URL. You can use it to read, set, or modify query parameters dynamically within your application.
Example
const [searchParams, setSearchParams] = useSearchParams(); const query = searchParams.get("query");
Let’s build an application that implements a user search page.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘query-parameters-demo’.
Project structure looks like below.
Step 2: Navigate to the project directory and install react router dom by executing below commands.
cd query-parameters-demo npm install react-router-dom
Step 3: Create pages folder in src folder and define UserProfile page and UserSearch page.
UserProfilePage.jsx
import { Link, useSearchParams } from "react-router-dom";
let users = [
{ id: "1", name: "Krishna", age: 36 },
{ id: "2", name: "Ram", age: 39 },
];
function getUser(id) {
for (let user of users) {
if (user.id === id) {
return user;
}
}
return undefined;
}
export default function UserProfilePage() {
const [searchParams, setSearchParams] = useSearchParams();
const id = searchParams.get("userId");
let user = getUser(id);
if (user === undefined) {
return (
<>
<h3>User details not found</h3>
<Link to="/">Click here to search users</Link>
</>
);
}
return (
<>
<h3>User Details</h3>
<ul>
<li>Id: {user.id}</li>
<li>Name: {user.name}</li>
<li>Age: {user.age}</li>
</ul>
<br />
<Link to="/">Click here to search users</Link>
</>
);
}
UserSearchPage.jsx
import { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function UserSearchPage() {
const [userId, updateUserId] = useState(1);
const navigate = useNavigate();
return (
<>
<form
onSubmit={(event) => {
event.preventDefault();
let url = "/user-profile?userId=" + userId;
navigate(url);
}}
>
<label htmlFor="userId">Enter User Id</label>
<input
type="text"
placeholder="userId"
value={userId}
onChange={(event) => {
updateUserId(event.target.value);
}}
/>
<br />
<br />
<button>Fetch User Details</button>
</form>
</>
);
}
Step 4: Update App.jsx with below content.
App.jsx
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";
import UserSearchPage from "./pages/UserSearchPage";
import UserProfilePage from "./pages/UserProfilePage";
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route path="/user-profile" element={<UserProfilePage />} />
<Route path="/" element={<UserSearchPage />} />
</Routes>
</BrowserRouter>
</>
);
}
export default App;
Step 5: Update main.jsx with below content.
main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>
);
Step 6: Build and run the application by executing below commands.
cd query-parameters-demo npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you will see below screen.
Enter the user id (for ex: 1) and click on the button ‘Fetch User Details’ to get the user details.
You can download the application from this link.
Previous Next Home
No comments:
Post a Comment