Prem
Prem

Reputation: 5987

Why button click event triggered automatically on page load - React.js

The following is the sample code written in React.js.

I am aware that passing the function to onClick event instead of calling the function can resolve this issue.

But what I can't understand is why onClick event is triggered on page load itself and prompting the alert by invoking the handleRemoveAll() method. Is this due to this.handleRemoveAll() is invoked at the global context? I am trying to understand how react.js works.

class IndecisionApp extends React.Component {
  render() {
      const options = ['One', 'Two', 'Three'];
      return (
        <div>
            <Options options={options}/>
        </div>
      )
  }
}
class Options extends React.Component {
    handleRemoveAll() { 
        alert('Are you sure you want remove all?');
    };
    render() {
       return (
            <div>
                <button onClick={this.handleRemoveAll()}>Remove All</button>
                {
                    this.props.options.map((option) => <Option key={option} optionText={option} />)
                }
            </div>
        )
    }
}
ReactDOM.render(<IndecisionApp />, document.getElementById('app'));

Upvotes: 1

Views: 4467

Answers (2)

Rohith Murali
Rohith Murali

Reputation: 5669

The onClick expects a function object, not a function call. This is same as assigning a function Vs assigning its return value.

function foo(){
   return 5*5;
}

1)var obj = foo; 2)var obj = foo();

In case 1, you are assigning the function and in case 2 you are assigning the return value of foo(), ie, 25. So in case 2 like the above snippet the function will be called.

Upvotes: 5

Rajnish Katharotiya
Rajnish Katharotiya

Reputation: 11

In reactJs if you write the function directly in component it means "this" keyword is refer to window. and that's why it's loading while page load.

So, try the below thing:

  • make a constructor method into component and then bind the function which you created.
  • And also use "this" keyword while making function.

I hope i did understood your question proper though you can try below suggestion or make clear your question.

constructor(props) {
        super(props);
this.handleRemoveAll = this.handleRemoveAll.bind(this);
    this.handleRemoveAll = () => { 
        alert('Are you sure you want remove all?');
    };
}

Upvotes: 0

Related Questions