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>
    );
  }
}

1 Answer 1

1

first of all you need to do this:

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

this will stop it being invoked immediately

Sign up to request clarification or add additional context in comments.

1 Comment

That fixed it thanks. I will accept when the system allows me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.