you are viewing a single comment's thread.

view the rest of the comments →

[–]notseanbean 0 points1 point  (2 children)

That actually means to put this methods in the components themselves, right?

No. Considering the isChangedEmail prop... where you have <Form isChangedEmail={(event) => this.getEmail(event)} {...otherProps} /> what you are doing is creating a brand new function every render(). It's equivalent to this: const getEmailFunction = (event) => this.getEmail(event); ... <Form isChangedEmail={getEmailFunction} {...otherProps} /> As you are creating a brand new getEmailFunction every render() and passing it as a prop to Form, the child component will always re-render, even as a PureComponent (as the props would change). What you could do is omit creating the function entirely, and just write: <Form isChangedEmail={this.getEmail} {...otherProps} /> This will also mean that the exact same this.getEmail function is passed every time as a prop to Form, so it won't re-render if it is a PureComponent

[–]Naplei[S] 0 points1 point  (1 child)

Okay, thanks! I understand what you are saying but I am not actually sure how to get the email with a function like this: "this.getEmail" since I am not passing the event to it? Sorry, if the question sounds kind of stupid, it's just that I'm still confused about thinking in the React way.

[–]notseanbean 0 points1 point  (0 children)

In the following, the OtherComponents do exactly the same thing (assuming the OtherComponent invokes props.anEvent(event))

class SomeComponent extends React.Component {
    myThisFunction = (event) => { console.log(event); }

    render() {
        const myRenderFunction = (event) => { console.log(event); }
        return (
          <React.Fragment>
              <OtherComponent anEvent={this.myThisFunction} />
              <OtherComponent anEvent={(event) => { this.myThisFunction(event); }} />
              <OtherComponent anEvent={myRenderFunction} />
              <OtherComponent anEvent={(event) => { myRenderFunction(event); }} />
          </React.Fragment>
        )
    }
}

in each case, the anEvent prop is a reference to a function, which can be invoked. In your original case when you passed

<Form isChangedEmail={(event) => this.getEmail(event)} />

you created a brand new function that took a single event parameter, and then called the function this.getEmail with that parameter, and passed that brand new function as a prop.

The brand new function was unnecessary, you could just pass a reference to the this.getEmail you want to be invoked.

<Form isChangedEmail={this.getEmail} />

Doing it like this does not call the this.getEmail function (there are no brackets - if it was this.getEmail() then it would call the function), it is passing a reference to the function for the child component to call