Fausto70
Fausto70

Reputation: 551

onChange event not working when build html code by function - REACTJS

I have a .js file with a component code that build a page containing:

Just consider that I need to build the combobox html by a function (in the real life I have some algorithms in order to build the html code of filters). When a combobox item is selected it should be called the "handleChange()" function. This code doesn't work because the "handleChange()" function is not called, nothing happen when I select a combobox item.

Moreover, if I have a look to the page analysis of browser I get:

<select onchange="{function handleChange(event) {
    var VALUE = event.target.value;
    console.log('VALUE=' + JSON.stringify(VALUE));
  }}"  name="2" value="1" size="sm" classname="text-center"  >
  <option value="1">AAAAA</option>
  <option value="2">BBBBB</option>
  <option value="3">CCCCC</option>
</select>

How can I solve this problem?

Upvotes: 0

Views: 56

Answers (2)

Amit
Amit

Reputation: 311

Yeah Nicholas Tower is right. If you still want to do it your way, then you need to remove the double quotes to make it work.

const build_CodiceHtml = (HANDLE_onChange__Arg ) => {
  let HTML_CODE= `
  <select onChange="(${HANDLE_onChange__Arg})(event)" name="MY_NAME" value="MY_VALUE" size="sm" className="text-center"  >';
    <option value="1">AAAAA</option>
    <option value="2">BBBBB</option>
    <option value="3">CCCCC</option>
  </select>`

  return  HTML_CODE;
}

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85012

I don't see a reason why dangerouslySetInnerHTML is needed. dangerouslySetInnerHTML is an escape hatch that's occasionally needed to bypass react and put raw html onto the page, but if you can stick to using standard react JSX elements, that will make your code simpler (not to mention safer). It will also fix your onChange issue, because react will hook up the onChange function for you.

For example:

const build_CodiceHtml = (HANDLE_onChange__Arg) => {
  return (
    <select
      onChange={HANDLE_onChange__Arg}
      name="MY_NAME"
      value="MYVALUE"
      size="sm"
      className="text-center"
    >
      <option value="1">AAAAA</option>
      <option value="2">BBBBB</option>
      <option value="3">CCCCC</option>
    </select>
  );
};

const getTableFiltri = () => {
  return (
    <table
      cellPadding="20"
      style={{
        border: "1px solid black",
        marginLeft: "auto",
        marginRight: "auto",
      }}
    >
      <tbody>
        <tr className="justify-content-md-center">
          <td>{build_CodiceHtml(handleChange)}</td>
        </tr>
      </tbody>
    </table>
  );
};

// ...
<Modal.Body className="modalBody">
  <div>{getTableFiltri()}</div>
  {getTableWithValue()}
</Modal.Body>;

Upvotes: 2

Related Questions