gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
how do i read query parameters in react
- User
how do i read query parameters in react
- Assistant
In React, you can read query parameters by using the
useParams()hook from the React Router package.Here's an example:
- Import the
useParamshook from thereact-router-dompackage:
import { useParams } from 'react-router-dom';- Use the
useParams()hook in your functional component to get the query parameters:
function MyComponent() { const { id } = useParams(); // `id` is the value of the `id` query parameter // e.g. if the URL is /example?id=123, `id` will be '123' // Rest of your component code... }- To use it, you need to define the routes in your
Router/Switchcomponents:
<Switch> <Route exact path="/" component={Home} /> <Route path="/example" component={MyComponent} /> </Switch>- Now you can access the query parameter in your URL by accessing the
idvariable:
http://localhost:3000/example?id=123In this example,
idis equal to "123". - Import the