Can someone check code for sending variable from Child to Parent in react?

I don’t know why but this does not sit right with me even though it works. Can someone double check my code?

Expected: User makes a selection in Child component. That selection should be sent up to Parent where it will be incorporated into other code.

Actual: As expected, no worries there.

My question is: am I coding this the right way?

Child component:

import React, { useState, Fragment } from "react";

const Autocomplete = (props) => {

//a bunch of code

function onKeyDown(e) {
    if (e.keyCode === 13) {
     //...
      setUserInput(filteredOptions[activeOption]);
      sendIngredients(filteredOptions[activeOption]);
//...
}

// a bunch of code

 function sendIngredients(ingredient) {
    props.parentCallback(ingredient);
  }

//more code


return (
    <Fragment>
      <div className="search">
        <input
          type="text"
          className="search-box"
          onChange={onChange}
          onKeyDown={onKeyDown}
        />

}

Parent component:

function IngredientPickerHooks(props) {
//....

function callbackSetIngredients(ingredientChild) {
    console.log(ingredientChild); //something will be done with this
//...   
    }

return (
//...
 <Autocomplete
          parentCallback={(ingredientChild) =>
            callbackSetIngredients(ingredientChild)
          }
        />
//...
);
}

The part that seems wrong to me is that I have added ingredientChild in parentCallback. I feel like there is a cleaner way to do this.

I haven’t tried it, but it looks basically right. My only thing would be that:

          parentCallback={(ingredientChild) =>
            callbackSetIngredients(ingredientChild)
          }

could be simplified to:

          parentCallback={ callbackSetIngredients }

JS is smart enough to know to take whatever is being sent as the first parameter and give it to the function as the first parameter. Both do basically the same thing, but yours adds a layer of complexity by wrapping it in an anonymous function. Sometimes you do need to do that - like if you need to inject parameters that aren’t coming from the calling site - but not here.

Is it weird to do this? Sure. But that is functional programming - passing functions back and forth. But doing this gets to be a pain in large apps which is one of the big problems redux solves.

1 Like