user18617901
user18617901

Reputation:

ReactJS Not being able to return the input received with the Search Bar

I made a simple searchbar with Reactjs. I need a small change in the searchbar I made, but I couldn't get what I wanted. What I want to do is to return the input given to the searchbar in the code below and print it as "You searched for ...." on the page. I keep the input I get in the searchbar in the searchItem in the code below.

How can I return the SearchItem and show it to the user?

I put the relevant part of the code to avoid confusion

const handleSearch = e => {
    const searchItem = e.target.value

    console.log(searchItem)

    const searchedProducts = products.filter(item => item.productName.toLowerCase().includes(searchItem.toLowerCase()))

    setProductsData(searchedProducts)
  }

  
  return (
    <Helmet>
      <CommonSection title={'Products'}/>
        <section>
          <Container>
            <Row>
            
            <Col lg='3' md='3'>
              <div className="filter__widget">
                  <select>
                    <option>Sort by</option>
                    <option value='ascending'>Ascending</option>
                    <option value='descending'>Descending</option>
                  </select>
                </div>
            </Col>
            <Col lg='6' md='6'>
              <div className="search__box">
                <input type='text' placeholder='Search...' onChange={handleSearch}/>
                <span><i class='ri-search-line'></i></span>
              </div>
              <div >
              <THIS AREA RETURN SEARCH BAR INPUT>
              </div>
            </Col>
          </Row>
          </Container>
        </section>

        <section className='pt-0'>
          <Container>
            <Row>
              {productsData.length === 0 ? (
                <h1 className='text-center fs-4'>No products are found!</h1>
              ) : (
                <ProductList data = {productsData} />
              )
            }
            </Row>
          </Container>
        </section>
    </Helmet>
  );
};

export default Shop;

This is how I should return it to the user: enter image description here

Upvotes: 0

Views: 38

Answers (1)

HenryDev
HenryDev

Reputation: 4983

What you could do is set the state of what the user is entering like this:

const [userInput, setUserInput] = useState('');

Then in your function you can simply set its value:

const handleSearch = e => {
   const searchItem = e.target.value

   setUserInput(searchItem); // You need to add this to set the value entered

   console.log(searchItem)

   const searchedProducts = products.filter(item => 
   item.productName.toLowerCase().includes(searchItem.toLowerCase()))

   setProductsData(searchedProducts)
 }

Finally, you can print out userInput anywhere you want to as this will hold the value entered by the user. Example:

<div>{userInput}</div>

Hope that helps :)

Upvotes: 1

Related Questions