1

I have converted a React class component to a function component with help from this question.

Everything works apart from this button:

{/* 
            Show only if user has typed in search.
            To reset the input field, we pass an 
            empty value to the filterUpdate method
          */}
{hasSearch && <button onClick={filterUpdate}>Clear Search</button>}

When I click this I get [object Object] in the search box. I also tried:

{hasSearch && <button onClick={filterUpdate("")}>Clear Search</button>}

but this stops the search functionality working. This is the old (Class component) code (which is working).

 {hasSearch && (
            <button onClick={this.filterUpdate.bind(this, "")}>
              Clear Search
            </button>
          )}

All of the code is in the other question. This provides context though.

 // update filterText in state when user types
  const filterUpdate = (value) => {
    setfilterText(value);
  };


/* ###################### */
/* ##### Search bar ##### */
/* ###################### */

// need a component class here
// since we are using `refs`
class Search extends Component {
  render() {
    const { filterVal, filterUpdate } = this.props;
    return (
      <form>
        <input
          type="text"
          ref="filterInput"
          placeholder="Type to filter.."
          // binding the input value to state
          value={filterVal}
          onChange={() => {
            filterUpdate(this.refs.filterInput.value);
          }}
        />
      </form>
    );
  }
}
nipy
  • 5,138
  • 5
  • 31
  • 72

1 Answers1

1

first of all you need to do this:

<button onClick={() => filterUpdate("")}> Clear Search</button>

this will stop it being invoked immediately

Red Baron
  • 7,181
  • 10
  • 39
  • 86