I'm experimenting with ReactiveSearch and using the ReactiveList component.
I'm trying to figure out how I can navigate though my React app and still be able to search.
Say I'm on the home route '/', use DataSearch component for autocomplete and that takes me to the results page '/results but I don't get any results!!
In order to get results, I have to search and stay on the '/results' page. Is there a prop that I'm missing on my DataSearch component in the Header:
<DataSearch
componentId="SearchSensor"
dataField={["original_title"]}
className="search-bar"
showIcon={true}
iconPosition="right"
innerClass={{
title: "text-title",
input: "text-input",
list: "text-item"
}}
/>
Again, in order to get results, I have to search from the DataSearch component that I have on the results page. Search doesn't work when I have search from the DataSearch component that is in the Header.
So how can I set it to be able to perform a search from any route that I might be on (searching from the DataSearch component that is in the Header for instance)?
Here you would be only using the DataSearch for autocomplete and then redirecting to the results page for the actual results. For this you could use the onValueSelected prop on DataSearch docs:
onValueSelected is called with the value selected via user interaction. It works only with autosuggest and is called whenever a suggestion is selected or a search is performed by pressing enter key. It also passes the cause of action and the source object if the cause of action was 'SUGGESTION_SELECT'.
So you can get the selected value on the homepage, and then use it for doing a search on the results page. This value can be stored in your component's state for doing search or you can add a DataSearch in your results page too and use the URLParams prop to set its value from the url. For example:
Home Page
<DataSearch
...
componentId="q"
onValueSelected={(val) => Router.push(`?q=${val}`)} // using nextjs router here for example
/>
Results Page
<DataSearch
...
componentId="q" // will set its value from the param 'q'
URLParams
className="hidden" // adding some CSS to hide it if not needed
/>
<ReactiveList
...
react={{
and: ['q']
}}
/>
Alternatively, you could use the onValueSelected on homepage to set the selected value in state (or store) and then query the ReactiveList on results page with defaultQuery prop docs.
Related
I have a page that displays products returned from my API based on the URL's search parameters. For example, '/products?search=socks' would return products with the word socks in the title. The search bar is located in the header. If I search for a product on the home page (a different path: '/'), it navigates to the product list page and displays the products. However, if I search for a product on the product list page (the same path: '/products'), it re-renders and removes the search parameters, leading to no products being displayed. I prefer to use current hooks as it appears useHistory is outdated.
I have tried to navigate to the URL directly:
navigate(`/products?search=${search}`);
And I have tried to set the parameters as one source suggested:
const params = new URLSearchParams();
params.set('search', search);
navigate(`/products?search=${search}`);
I expected the query/search parameter to replace the search value and re-render with the new results.
I would use the new React Router V6 useSearchParams hook:
import { useSearchParams } from 'react-router-dom'
Then instantiate the hook at the top of your component:
let [searchParams, setSearchParams] = useSearchParams();
Then you can manipulate the search params anywhere, in your case:
setSearchParams({ search: '...' );
Doing this along-side the navigate() call will basicallly lead the user to the page as the search param is being changed.
In your situation, I would detect if the user is already on the product list page before always running navigate(). You can use the useLocation() hook to detect what pathname you currently are on.
If you're on the product list page already, don't run navigate(). Your useEffect would be responsible for re-rendering the page when search params change using a dependency array [searchParams.search]:
useEffect(() => {
// do stuff when search params "search" variable changes
}, [searchParams.search])
for a project I am working on I am running into a problem with the nextjs Router.I have a component that has an input field which the user should be able to input their searchterm in. There is a different component which should be able to get this searchterm and perform a search.
Because the two components aren't connected I would like to set the queryParameters in the router in the Input component, and then execute a function in the search component when the searchTerm is changed.
The problem lies in the following: The searchComponent receives the nextJS router as props and will only execute my useEffect function when those props are changed (and react knows they are changed), on top of that I need to stay on the same page when updating the query parameters, but the route of this page is dynamic. For example: the user can add this combination of components on /search but also on /lookforitem.
I have tried setting the queryParameters in the following way in the Input component:
function setQueryParams() {
router.query = {
...router.query,
searchTerm: input.current,
};
}
In combination with the following code in the Search component:
useEffect(() => {
console.log('Router has changed');
}, [router]);
The problem is that this useEffect doesnt get called untill the search component is rendered again (I have created a button that logs the router to the console, and it shows the updated router), which I assume is because React hasn't realised that the Router props have changed.
I have also tried setting the query parameters via a router.push in the following way:
function setQueryParams() {
router.push(
{
pathname: router.route,
query: {
...router.query,
searchTerm: input.current,
},
},
undefined,
{ shallow: true }
);
}
However this comes with its own set of problems. First of all it causes a refresh of the page, which I don't want. On top of that it changes the url to for example: /search?searchTerm=Hello which means that if I enter a different input and submit it will stack making the next url for example: &searchterm=hello?searchterm=goodbye.
I want a way to update the query parameters without refreshing the page, but while also notifying the other components that use the router that the query parameters have updated. All of the searching that I've done seems to be specific to either routing to a different page or routing to a predefined page.
Any help would be greatly appreciated.
I have a ReactiveList component that lives in my SearchContainer. All it does is display search results based on user query. The ReactiveList component works, it automatically displays the contents of my ES index (hosted at Appbaseio). It DOES NOT display results based on user submitted query.
In my global Navbar I have a DataSearch component (conditionally rendered based on route) that provides autocomplete. I also have a pretty much identical DataSearch component in my homepage at ('/').
I'm trying to figure out how to pass the query from DataSearch to ReactiveList so that the results displayed are actually based on a user submitted query?
So let me reiterate, I'm trying to figure out how to get DataSearch and ReactiveList to talk to each other.
In my DataSearch component, I have
<DataSearch
componentId="q"
URLParams={true}
onValueSelected={(value, cause, source) => {
if (cause !== 'SUGGESTION_SELECT') {
<Redirect to={{
pathname: '/search',
search: `?q=${value}`
}}/>;
} else {
this.valueSelected = true;
}
}}
...
/>
In my ReactiveList component I have:
<ReactiveList
componentId="q"
URLParams={true}
onNoResults="Sorry, no results were found, try searching again."
react={{ or: ["q"] }}
onData={(res) => { ... }}
...
/>
From what I understand, as long as I have URLParams={true} in DataSearch and componentId='q' in both DataSearch and ReactiveList - search should work. Autocomplete seems to be functional but ReactiveList is NOT displaying results based on user query.
Do I need to add another property to DataSearch or ...? Where am I going wrong.
Different components should not have the same ID. Set the componentId for your ReactiveList to something unique (and choose a different unique ID for your DataSearch).
Not sure if there is another problem in the setup but this is something you can fix right away.
According to the accepted answer to this question, React Router 4 doesn't match query parameters anymore. If I go from a URL matched by one of my <Route>s to the same URL with a different query string, the content doesn't seem to change. I believe this is because navigating between URLs that match the same <Route> doesn't change the content, but please correct me if I'm wrong. Given this, how do I use React Router for a set of URL's that need to differ only by query parameter?
For example, many search engines and other sites that use search bars, including the site I am working on, use a query parameter, commonly q or query. The user may search for one thing, then decide that is not what he/she wants and search for another thing. The user may type in the second URL or search with the search bar again. There isn't really a place for the search term in the URL path, so it kind of needs to go in the query string. How do we handle this situation?
Is there a way, with React Router, to link to a URL that only differs in the query string and change the content, without refreshing the entire page? Preferably, this wouldn't require any external library besides React and React Router.
Try the render function prop instead of component prop of Route. Something like this:
<Route render={props => {
// look for some param in the query string...
const useComponentA = queryStringContains('A');
if(useComponentA) {
return <ComponentA {...props}/>;
} else {
return <ComponentB {...props}/>;
}
}}/>
There are 2 ways to do that:
1) Use location.search in react component to get the query string, then pass it to child component to prevent re-rendering the whole component. React-router has the official example about this.
2) Define a regex path of router to catch the query string, then pass it to react component. Take pagination as an example:
routes.js, for router config you can refer this
const routerConfig = [
{
path: '/foo',
component: 'Foo',
},
{
path: '/student/listing:pageNumber(\\?page=.*)?',
component: 'Student'
},
Student.js
render() {
// get the page number from react router's match params
let currentPageNumber = 1;
// Defensive checking, if the query param is missing, use default number.
if (this.props.match.params.pageNumber) {
// the match param will return the whole query string,
// so we can get the number from the string before using it.
currentPageNumber = this.props.match.params.pageNumber.split('?page=').pop();
}
return <div>
student listing content ...
<Pagination pageNumber = {currentPageNumber}>
</div>
}
Pagination.js
render() {
return <div> current page number is {this.props.pageNumber} </div>
}
The 2nd solution is longer but more flexible. One of the use cases is server sider rendering:
Apart from the react components, the rest of the application (e.g. preloaded saga) need to know the url including query string to make API call.
I have a usecase where I have a list of elements inside some component similar to vanilla html select. I want, when user clicks on any of the element inside list, route should change. Can I use some regex while defining route and change route by using some API method from react router, onValueChange event of select?
Example
Root route: /
List Data: Cat, Dog, Elephant
When someone clicks on Cat I want him to get navigated to /Cat, similarly /Dog, /Elephant.
So after talking about it for a bit. figured out what you were wanting to do.
you need to define a new route in react-router that you can use for this history change.. something like this:
<Route exact path="/:name" component={SomeComponent} />
in your component you have access to this "name" via this.props.params.name
you can also call an action to update the store before updating this route
Note: if you stay with v2... You should make your actions return a promise, so that you can just chain the event in your component. aka:
onChange={this.handleChange}
handleChange = (value) => { // assuming you have the value here.. it may be e is the function param and you get the value as e.target.value
this.props.saveSelectedAnimal(value).then( () => {
this.props.history.push("/");
})
}