skip to Main Content

//Navbar.jsx

const [query, setQuery] = useState("")
const handleChange = (e) => {
setQuery(e.target.value) }
.
.
.
<input value={query} id="query" onChange={handleChange} />

Now my question is, I have a separate route ("/search/:query", component is Search.jsx). How do I send the ‘query’ state from the navbar to this route so that I can extract the query from the params and use it afterwards?

Basically it’s a movie site and I have a search bar at the home page (in navbar) and a separate page for searching too but I want the search parameter in home page/navbar to be sent to that search page route for params extraction

I thought of prop sending but that wouldn’t work since I’m sending data to the params of the url, so I’m pretty clueless

I am using react-router

2

Answers


  1. Of course you can use props. Use this in your search.jsx page:

    const { query } = props.match.params;
    

    now with a simple code you can get the data you want:

    useEffect(()=>{
        searchFunction(query)
    },[]);
    

    if this doesn’t work for you, try this:

    const query  = this.props.location.state
    
    Login or Signup to reply.
  2. -> Follow my code :-

    ->Navbar.jsx :-

    import React, { useState } from "react";
    import { useHistory } from "react-router-dom";
    
    const Navbar = () => {
      const [query, setQuery] = useState("");
      const history = useHistory();
    
      const handleChange = (e) => {
        setQuery(e.target.value);
      };
    
      const handleSubmit = (e) => {
        e.preventDefault();
        // Navigate to the search page with the query parameter
        history.push(`/search/${query}`);
      };
    
      return (
        <nav>
          <form onSubmit={handleSubmit}>
            <input value={query} id="query" onChange={handleChange} />
            <button type="submit">Search</button>
          </form>
        </nav>
      );
    };
    
    export default Navbar;
    

    -> In your Search.jsx component,you can access this query parameter using React router useParams hooks.

    -> Search.jsx :-

    import React from "react";
    import { useParams } from "react-router-dom";
    
    const Search = () => {
      const { query } = useParams();
    
      // Use the query parameter in your component
      return (
        <div>
          <h1>Search Results for: {query}</h1>
          {/* Render search results here */}
        </div>
      );
    };
    
    export default Search;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search