skip to Main Content

I need a better understanding of how JavaScript functions work with React.

I have a "Button" with an "onClick" event that I want to "reset" an "input" text field. I just can’t get it to work.

Solution: When the "Reset" button is clicked, the "SearchText" input text field is cleared of any characters.

Code


import { useCallback, useState } from 'react';
import { faMagnifyingGlass, faPeopleGroup, faBuildingUser, faArrowsRotate } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import utilStyles from '../styles/utils.module.css';

const SearchText = ({ cards, setSearchResults, setEnteredText }) => {

  const enteredText = ' ';

  const onChangex = useCallback((event) => {
    var enteredText = event.target.value;
    setEnteredText(enteredText);
  }, []);

  const onFormSubmit = (event) => {

    event.preventDefault();

  }
  
  const onChange = (event) => {

    if (!event.target.value) return setSearchResults(cards);

    const fields = ['NAME', 'CAMPUS', 'DEPARTMENT', 'JOBTITLE'];
    const query = event.target.value.toLowerCase();

    const filterData = (cards, fields, query) => {
      return cards.filter(record => fields.some(field => record[field]?.toLowerCase().includes(query)));
    };

    setSearchResults(filterData(cards, fields, query));

  }

  const onReset = (event) => {

    console.log("Clicked Reset");
    const container = document.getElementById("SearchText");
    container.reset();

  }

  const resetSearchInput = (event) => {

    console.log("Clicked");
    var enteredText = event.target.value;
    setEnteredText(enteredText);

  }


  return (
      
    <>
      
      <form id='EmployeeSearchText' onSubmit={onFormSubmit}>
        <div className="container-fluid p-3">
          <div id='Row1' className={`row ${utilStyles.divPadding}`}>
            <div id='Row1Column1' className="col">
              <div id='SearchText-container' className={utilStyles.searchBar}>
                <FontAwesomeIcon icon={faMagnifyingGlass} className={utilStyles.icon} />
                <input id='SearchText' type="text" onChange={onChange} className={`form-control ${utilStyles.inputField} ${utilStyles.inputPadding}`} name="SearchText" placeholder="Search Last Name; First Name; Campus; Deparment....." />
              </div>
            </div>
          </div>
          <div className='text-center'>
            <div id='Row2' className={`row ${utilStyles.divPadding}`}>
              <div id='Row2Column1' className="col">
                <div id='Employees-container'>
                  <button id='EmployeeListing' className={utilStyles.btnYellow}>Employees&nbsp;&nbsp;<FontAwesomeIcon icon={faPeopleGroup} /></button>
                </div>
              </div>
              <div id='Row2Column2' className="col">
                <div id='DepartmentListing-container'>
                  <button id='DepartmentListing' className={utilStyles.btnYellow} type="button">Department Listing&nbsp;&nbsp;<FontAwesomeIcon icon={faBuildingUser} /></button>
                </div>
              </div>
              <div id='Row2Column3' className="col">
                <div id='SearchTextReset-container'>
                  <button id='SearchTextReset' onClick={onReset} className={utilStyles.btnGrey} type="button">Reset&nbsp;&nbsp;<FontAwesomeIcon icon={faArrowsRotate} /></button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>     
      
    </>
  
  )
}

export default SearchText;

2

Answers


  1. You can use controlled components on your text!

    1 – Create a State for your input

    2 – Add the State you created as a value on your input

    3 – Use the OnChange to change the State to the value you typed

    4 – Just use the OnClick on the button to reset the State to an empty string

    OBS: I changed the OnClick to just reset the state, if you want your full function just add changeTextInput("") to it

    const [textInput,changeTextInput] = useState("") // Creating a state
    
      const onChange = (event) => {
    
        if (!event.target.value) return setSearchResults(cards);
        
        changeTextInput(event.taget.value) // Changing the state when typing on the input
       
        const fields = ['NAME', 'CAMPUS', 'DEPARTMENT', 'JOBTITLE'];
        const query = event.target.value.toLowerCase();
    
        const filterData = (cards, fields, query) => {
          return cards.filter(record => fields.some(field => record[field]?.toLowerCase().includes(query)));
        };
    
        setSearchResults(filterData(cards, fields, query));
    
      }
    
    
      return (
          
        <>
          
          <form id='EmployeeSearchText' onSubmit={onFormSubmit}>
            <div className="container-fluid p-3">
              <div id='Row1' className={`row ${utilStyles.divPadding}`}>
                <div id='Row1Column1' className="col">
                  <div id='SearchText-container' className={utilStyles.searchBar}>
                    <FontAwesomeIcon icon={faMagnifyingGlass} className={utilStyles.icon} />
                    <input value={textInput} id='SearchText' type="text" onChange={onChange} className={`form-control ${utilStyles.inputField} ${utilStyles.inputPadding}`} name="SearchText" placeholder="Search Last Name; First Name; Campus; Deparment....." /> // Adding the value and the OnChange function
                  </div>
                </div>
              </div>
              <div className='text-center'>
                <div id='Row2' className={`row ${utilStyles.divPadding}`}>
                  <div id='Row2Column1' className="col">
                    <div id='Employees-container'>
                      <button id='EmployeeListing' className={utilStyles.btnYellow}>Employees&nbsp;&nbsp;<FontAwesomeIcon icon={faPeopleGroup} /></button>
                    </div>
                  </div>
                  <div id='Row2Column2' className="col">
                    <div id='DepartmentListing-container'>
                      <button id='DepartmentListing' className={utilStyles.btnYellow} type="button">Department Listing&nbsp;&nbsp;<FontAwesomeIcon icon={faBuildingUser} /></button>
                    </div>
                  </div>
                  <div id='Row2Column3' className="col">
                    <div id='SearchTextReset-container'>
                      <button id='SearchTextReset' onClick={changeTextInput("")} className={utilStyles.btnGrey} type="button">Reset&nbsp;&nbsp;<FontAwesomeIcon icon={faArrowsRotate} /></button> //Clearing the state when clicked
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </form>     
          
        </>
      
      )
    }
    
    export default SearchText;
    
    Login or Signup to reply.
  2. If you want to clear filter values you may achieve this following method.

    1. Create a state for that filter.
      const [filterValue, setFilterValue]= useState(”)
    2. set state when your onchange function trigger.
      const onChange = (event) => {
        setFilterValue(event.target.value)
        if (!event.target.value) return setSearchResults(cards);
    
        const fields = ['NAME', 'CAMPUS', 'DEPARTMENT', 'JOBTITLE'];
        const query = event.target.value.toLowerCase();
    
        const filterData = (cards, fields, query) => {
          return cards.filter(record => fields.some(field => record[field]?.toLowerCase().includes(query)));
        };
    
        setSearchResults(filterData(cards, fields, query));
    
      }
    
    1. update input value according to this:
                    <input id='SearchText' type="text" value={filterValue}  onChange={onChange} className={`form-control ${'utilStyles.inputField'} ${'utilStyles.inputPadding'}`} name="SearchText" placeholder="Search Last Name; First Name; Campus; Deparment....." />
    
    1. Clear state on reset button click.
     const onReset = () => {
        setFilterValue('')
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search