Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

how do i read query parameters in react

  1. User

    how do i read query parameters in react

  2. Assistant

    In React, you can read query parameters by using the useParams() hook from the React Router package.

    Here's an example:

    1. Import the useParams hook from the react-router-dom package:
    import { useParams } from 'react-router-dom';
    
    1. 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...
    }
    
    1. To use it, you need to define the routes in your Router / Switch components:
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/example" component={MyComponent} />
    </Switch>
    
    1. Now you can access the query parameter in your URL by accessing the id variable:
    http://localhost:3000/example?id=123
    

    In this example, id is equal to "123".