jmona789 jmona789 - 2 months ago 10
React JSX Question

React- HTTP request is firing on page load

I'm just starting to use react and I have this login model component with the following:

export default class LoginModal extends Component {

constructor() {
super();
this.render.bind(this);
this.state = {showModal: false}
}

close() {
this.setState({ showModal: false });
}

open() {
this.setState({ showModal: true });
}

login() {
console.log("Hello. It's Me")
axios.post('https://crossorigin.me/http://requestb.in/w21igbw2', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
//this.setState({ showModal: false });
})
.catch(function (error) {
console.log(error);
});
}

handleSelect(eventKey) {
event.preventDefault();
alert(`selected ${eventKey}`);
}


In the model itself I have
<Button onClick={this.login()} bsStyle="btn btn-black btn-block">Login</Button>
, but the
login()
function fires as soon as the page loads not when the button is clicked. Am I doing this the correct way? Most of this code was written by a co-worker with more react experience than me so I may be putting the login function in the wrong place entirely. If so please let me know where the function should go.

Answer

this.login() should be given as this.loginto the onClick() handler

<Button onClick={this.login} bsStyle="btn btn-black btn-block">Login</Button>
Comments