2

I am attempting to dynamically create multiple select drop downs in a loop. The html-react-parser works fine when there is just pure html in it. However, when I add a onChange function to the select tag, it does not parse that part correctly. It actually seems to just disregard it.

 let selectOptions = "<th>Details</th>";
 for(var j=0;j<envsToCommitsHolder.length;j++){
        selectOptions += "<th><select onChange={(event) => {handleOptionSelection(event.target.selectedOptions)}} id="+realRepoName[j+1]+"><option>"+realRepoName[j+1]+"</option>";       
        for(var h=0;h<envsToCommitsHolder[j].val.length;h++){
          console.log(realRepoName[j+1]);
          console.log(envsToCommitsHolder[j].val[h]);    
          //var value = envsToCommitsHolder[j].val[h];      
          selectOptions += "<option value="+h+">"+envsToCommitsHolder[j].val[h]+"</option>";          
        }
        selectOptions += "</select></th>";      
      }     
      return parse(selectOptions);     

Please see the attached image to see how it is being rendered. It puts the javascript outside of the select tag altogether. Is there some other way I should be doing this? I have attached the image of how the select with the onChange is being rendered on the browser -> problematic part. I also saw there is a "dangerouslySetInnerHTML" to parse string and render html out of it, but I am not sure how to use that or if it will be useful in this case or not. Any help would be greatly appreciated. I am quite stuck with this one.

4
  • onChange={(event) => {handleOptionSelection(event.target.selectedOptions)}} this string will not work in pure HTML, ref: w3schools.com/jsref/event_onchange.asp. it only can be used with react Commented Jan 30, 2023 at 13:21
  • I am using react. Also, changing it to something like onchange="test()" does not work either. It completely just ignores that whole part. Commented Jan 30, 2023 at 14:17
  • yeah, when using React, I recommend should NOT make some changes to the DOM directly (not through React), it is not good to handle events relevant Commented Jan 30, 2023 at 14:44
  • @H294 How do you suggest I do this then? problem is, the data is coming in from API calls. So I have to create the select boxes dynamically. Commented Feb 1, 2023 at 15:49

1 Answer 1

1

I have created a sandbox to render the select options dynamically, you can custom the rendering on your own, https://codesandbox.io/s/react-typescript-forked-8psy13?file=/src/App.tsx
Basic React knowledge: useState, useEffect If y have a question, you can ask me here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.