0

Suppose there is a route like <base-url>/search

the route is defined like

import { Link, BrowserRouter as Router, Route } from "react-router-dom";
import { useHistory, useLocation } from "react-router-dom";
...
<Router>
  ...
  <Route path="/search/:searchInput">
     <Search />
  </Route>
</Router>

There is also a textbox component which uses a useContext hook and contextprovider, and onChange it keeps the current value of the textbox input which is used by the <Search/> component

how do you change the path name in real time to the name of the search input? if the textbox is empty it should default to <base-url>/search

for example if you type 'lil' in the textbox, the current route or pathname will redirect / render simultanously to <base-url>/search/lil

if there are multiple words or space in the textbox such as 'lil red', the current path will render immediately to <base-url>/search/lil%20red

do i need to use react <Link/>?

related thread How to update the url of a page using an input field?, react-router - how change the url

EDIT

import SearchContext from "../Search/context"

const Search = () => {
   const context = useContext(SearchContext)

   // context.searchInput is the value of the textbox provided by context.provider

   useEffect(() => {}, [])

   return (...)
}
export default Search
Ridhwaan Shakeel
  • 981
  • 1
  • 20
  • 39
  • `Link` is useful when you want to change route based on a user clicking something, if you want to change the route programmatically you can use `useHistory` and then use the history objects `push` or `replace` method to change routes. – Jacob Smit May 30 '21 at 21:33
  • what would be the place to push history and reflect changes on page since i added the search component edit above? Im new to `withRouter`, `useHistory` hook – Ridhwaan Shakeel May 30 '21 at 21:47

1 Answers1

1

This may not be the best answer, but with the information provided and the time I have to spend on it here is an example of how you could trigger a route update based on your context value.


import SearchContext from "../Search/context"
import { useHistory, useLocation } from 'react-router-dom';

const Search = () => {
    const context = useContext(SearchContext);
    const history = useHistory();
    const location = useLocation();

    // The below use effect will trigger when ever one of the following changes:
    //      - context.searchInput: When ever the current search value updates.
    //      - location.pathname: When ever the current route updates.
    //      - history: This will most likely never change for the lifetime of the app.
    useEffect(() => {
        let basePath = location.pathname;

        // As the available information does not pass a "Base Route" we must calculate it
        // from the available information. The current path may already be a search and
        // duplicate "/search/" appends could be added with out a small amout of pre-processing.
        const searchIndex = basePath.indexOf('/search/');

        // Remove previous "/search/" if found.
        if (searchIndex >= 0) {
            basePath = basePath.substr(0, searchIndex);
        }

        // Calculate new path.
        const newPath = `${basePath}/search/${encodeURI(context.searchInput)}`;

        // Check new path is indeed a new path.
        // This is to deal with the fact that location.pathname is a dependency of the useEffect
        // Changing the route with history.push will update the route causing this useEffect to
        // refire. If we continually push the calculated path onto the history even if it is the
        // same as the current path we would end up with a loop.
        if (newPath !== location.pathname) {
            history.push(newPath);
        }
    }, [context.searchInput, location.pathname, history]);

    return null;
}
Jacob Smit
  • 2,206
  • 1
  • 9
  • 19