BigHairDev BigHairDev - 4 months ago 64
React JSX Question

OnChange event for elements in html set with DangerouslySetInnerHTML in ReactJS

I have a json file with HTML Element (more than 20) details like, id, value, type, etc.

I am creating a big String with all the elements created and inserting it into my React JS component with 'DangerouslySetInnerHTML'. But, I want to use onChange event on these events.

finalStartingElementStructure += 'onChange=' + '"' + this.onChangeForAllElements + '"';

onChangeForAllElements(e) {
// console.log('onChange INVOKED', e);
}


This is not working for sure, but, I am out of options for calling onChange event on requirement.

I am a noob in React JS, please shed some light on it.

Answer

A solution that always work is using jQuery, ReactJS and jQuery are working well together. The following solution also works for dynamically generated elements.

$(document).on('change', 'your-selector', this.onChangeForAllElements);

onChangeForAllElements(e) {
   // console.log('onChange INVOKED', e);
}

But if you want to use React functionality I recommend to use the React way to create elements instead of using the insecure DangerouslySetInnerHTML method.