Search code examples
javascriptreactjssearchfull-text-searchhighlight

How give search functionality like Ctrl+F to a search input in react.js


I have a Admin.js file in which i have all the child component and a Search input, i want to give search functionality like Ctrl+F to it. So If user type any input inside this search input then it highlights the words i think onKeyUp will works.

In This File i have all components.

This is Admin.js

<nav>
       {/* <!-- Search --> */}
              <div className="navbar-nav align-items-center">
                <div className="nav-item d-flex align-items-center">
                  <i className="bx bx-search fs-4 lh-0"></i>
                  <input
                    type="text"
                    className="form-control border-0 shadow-none"
                    placeholder="Search..."
                    aria-label="Search..."
                  />
                </div>
              </div>
        {/* <!-- /Search --> */}
</nav>

           <Routes>
              <Route path="/" element={<Dashboard_panel />} />
              <Route path="/customer-details" element={<CustomerDetails />} />
              <Route path="/product-details" element={<ProductDetails />} />
              <Route path="/billing-details" element={<Billing />} />
              <Route path="/receipt-form" element={<ReceiptForm />} />
              <Route path="/bill-preview" element={<BillPreview />} />
              <Route path="/customer-ledger" element={<CustomerLedger />} />
              <Route path="/expense-details" element={<ExpenseForm />} />
              <Route path="/cash-book" element={<CashBook />} />
              <Route path="/company-account" element={<Account_Company_Balance />} />
            
            </Routes>

How can i implement this logic please help me. Thank you..


Solution

  • I suggest implement an eventListener within a useEffect hook, when someone press 'ctrl + f' it changes your Search component state, and a function with a map function that return what you're searching and highlith it, applying a span with a class that make it happen. This maybe wold help you out: https://www.npmjs.com/package/react-highlight-words

    Highlight text using ReactJS I hope it helps