radio buttons is not functioning properly

Viewed 97

a division has a checkboxs and by clicking that checkbox radio buttons options need to be shown for a particular checkbox checkbox is mapped as according to the array

<form id="lab_test_detail">
  {item.subcategory.map((item, index) =>
    <>
      <input type={"checkbox"} onChange={() => handleChange(item, index)} name={item.id}></input>
      <label style={{ position: "inherit", zIndex: "10" }}>{item.categoryname} </label>
      <div id={index}></div>
    </>
  )}
</form>

when the checkbox is changed radio buttons option should have to populate on

handleChange is

const handleChange = (item, index) => {
  httpClient.GET(`medical-institute/categoryId/${item.id}`, false, true)
    .then(resp => {
      // debugger;
      document.getElementById(index).innerHTML =
      `
      ${
        resp.data.data.map((item1,index1)=>{
          return`<form>
          <input type="radio" onChange=${handleRadioChange(item,index)}></input>
          <label >${item1.medicalinstitutename}</label>
          <span> Rs.${item1.price}</span>
          <br/>
          </form>
          `
        })
      }
  
      `
      console.log("response is", resp.data.data)
    })
}

const handleRadioChange = (item, index) => {
  console.log("inside radiochange")
  console.log("dasdas", item, index)
}

so when radio button is clicked i need to do a particular thing but handleRadioChange is called when i click on the checkox but not when i click on radio , why is this happening, a ny solution?

1 Answers
  1. Because you are executing the handleRadioChange once the node is added into the DOM.

Change the onChange handler

handleRadioChange(item,index)

to

() => handleRadioChange(item,index)
  1. You should try to work with the virtual DOM instead of insert html string. In your case, I think you can use state to store the item data for display and trigger the re-render. BTW you might don't have to fetch the data every time user clicks a check box.
Related