Need help with setState for onChange event

New(ish) to coding, took a Javascript Development class with General assembly and majority of the class went over React.js. I’m building side projects to stay fresh just in CodeSandbox - this one project I’m building is a page with all the meals I’ve cooked (with BlueApron) and I want to be able to sort based on protein.

I’ve created a select, but the onChange function seems to be running twice when the page loads, and then not at all when I change the option in the drop down? Any help would be great - here is my component for the select element:

function Sorter(props) {
  const proteins = [
    "All",
    "Pork",
    "Beef",
    "Lamb",
    "Shellfish",
    "Fish",
    "Poultry",
    "Vegetarian"
  ];

  const proteinList = proteins.map((d, i) => {
    return (
      <option value={d} key={i}>
        {" "}
        {d}
      </option>
    );
  });

  return (
    <div id="filter">
      Filter:&nbsp;
      <select
        id="proteinSelect"
        defaultValue={props.proteinSelected}
        onChange={console.log(this.value)}
      >
        {proteinList}
      </select>
    </div>
  );
}

Create a method called handleChange and set your onChange action to execute this method.

onChange={handleOnChange}

Your function looks like below

function handleChange(e){

    console.log(e.target.value)

  }

This didn’t work. It’s still running the handleChange function twice upon initial load, and then not at all on the actual change.

Here is the Code Sandbox if it helps:

You are doing this

onChange={handleOnChange()}

Here you are calling the function on this line. What you should do is pass a reference to the function so that when onChange event fires, it will call the function using reference. So change your code like below. Omit the ()

onChange={handleOnChange}

This seems like a really important subject that I don’t really have a full grasp on. Can you talk a little more about this or point me to some good reading material. I’m a little fuzzy on how this event gets passed back from inside the render function as just the name.

1 Like

Thanks! That worked!

I’m seconding @bradhanks - can you explain why () called the function? I’m going to build this out as a fay to only display the recipe “category” selected. My instinct would be to pass this.value into the function, but using e.target.value seems to working just as well.

Hi @bradhanks and @angusmc
I had the same problem when I started with React. If we passed in the function with parentheses, the function will execute every time the component renders.
Read this stackoverflow question for details regarding when to use () and when not to.

Also read this tutorial on how to create event handlers in React. Hope everything will be clear after reading this

1 Like