0

I'm not sure if React is explicitly relevant, other than that it requires me to explicitly bind the function which is calling .each().

But I have a submit() function for a dynamically generated form. I am using .each() to iterate through the various fields to get the data. As I understand, the callback I supply to .each() is supposed to become bound to the DOM element for the current iteration. Instead however, this is referring to the class that the submit() function is bound to. It looks roughly like:

class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.submit = this.submit.bind(this);
    }

    submit() {
        $('input.my-input').each(() => {
            console.log(this);
        });
    }
}

And my class object is being printed to the devtools console instead of the DOM element, ie.:

> MyClass {props:..., refs:..., state:...}

I'm assuming this is somehow an issue with submit() being bound. How can I otherwise work around this?

cebo
  • 688
  • 1
  • 8
  • 26
  • 1
    Why are you using DOM events in react? You should not really be manipulating the DOM in react, that is what react is for. – epascarello Jan 03 '22 at 18:24
  • 1
    Arrow functions have no explicit `this`. try `$('input.my-input').each(function() {console.log(this); });` – charlietfl Jan 03 '22 at 18:26
  • @epascarello Its a pretty situational popup form, only consisting of checkboxes/radios and the jQuery stuff is all read-only. jQuery just made for a lighter and more readable way to do what I wanted instead of dealing with the overhead of react state. – cebo Jan 03 '22 at 19:04

0 Answers0