educative.io

Educative

Callback Handlers in JSX

What does this mean, “We pass a function from one component (App) to another component (Search); we use it in the second component (Search); but use the actual callback of the function call in the first component (App).”

Let’s analyse it in-line.

  1. We pass a function from one component (App) to another component (Search);
    -> This refers to A, a callback function is introduced (passed to Search).
    // A
    const handleSearch = event => {
       // C
       console.log(event.target.value);
    };
    ...
    <Search onSearch={handleSearch} />
    ...
    
  2. we use it in the second component (Search);
    -> This refers to B, it is used elsewhere.
    ...
    setSearchTerm(event.target.value);
    
    // B
    props.onSearch(event);
    ...
    
  3. but use the actual callback of the function call in the first component (App).
    -> This refers to C, it “calls back” to the place it was introduced (in A).
    const handleSearch = event => {
    // C
    console.log(event.target.value);
    };
    

Hope his helps!