Search a result in next page reactjs

Viewed 488

I am having a search bar in my component. I want on click of search, it should call the search action and navigate the result to the parent component.

 <input 
              onKeyPress={(event) => {
             if (event.key === "Enter") {
                  this.onSearch(event.target.value);
                }
              }}
              type="text"
            />

Method:

 onSearch(searchString) {
     // perform Search
     this.props.history.push("/details");
  } 

I want it to navigate to a details page with the search String, in URL I am expecting something like: http://localhost:8080/details?search="searchString".

Can anyone help me with this?

2 Answers

You could do this

onSearch(searchString) {
  // perform Search
  this.props.history.push("/details?search=" + encodeURIComponent(searchString));
}

Hope this helps.

For me using router.push works and search query is passed with query parameter and pathname can contain which page you want to go navigate to.

Example:

Step 1: Importing useRouter:

import { useRouter } from "next/router";

Step 2: Create a router variable:

 const router = useRouter();

Step 3: Use in Event handler in Search(I am using Semantic UI) and using a state called searchText

const [searchText, setsearchText] = useState("");

You can use Input, I am using Search Component of Semantic UI here:


    <Search
              input={{ icon: "search", iconPosition: "left" }}
              showNoResults={false}
              selectFirstResult={true}
              placeholder="Search..."
              value={searchText}
              onSearchChange={(evt, data) => {
                setsearchText(data.value);
              }}
              onKeyPress={e => {
                if (e.key === "Enter") {
                  router.push({
                    pathname: "/listSearch",
                    query: {
                      searchQuery: searchText
                    }
                  });
                }
              }}
            />

Step 4: Now when the use for me press enter, onKeyPress will be called and the URL will be as below(listSearch here is a NextJS page):

http://www.localhost.com/listSearch?searchQuery=cds

Step 5: In the target page in my case listSearch you can put below code to get the search string:

import { useRouter } from "next/router";

...

const router = useRouter();
const searchQuery =
    router && router.query && router.query && router.query.searchQuery
      ? router.query.searchQuery
      : "";

Hope it helps

Related