I have a React-JS code:
class SideMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
inputNumber: '',
inputMessage: ''
};
this.getAccountInfo = this.getAccountInfo.bind(this)
}
getAccountInfo(props) {
console.log(props.inputNumber, props.inputMessage)
};
render() {
return(
<body className='SideMenuBg'>
<div className='SideMenu'>
<frame className='sideMenuBackgroundFrame'>
<input type='text' value={this.state.inputNumber} onChange={evt => this.updateInputNumber(evt)} placeholder='Number'/>
<input type='text' value={this.state.inputMessage} onChange={evt => this.updateInputMessage(evt)} placeholder='Message'/>
<button onClick={this.getAccountInfo(this.state)}>press me</button>
</frame>
</div>
</body>
)
}
updateInputNumber(evt) {
const val = evt.target.value;
this.setState({
inputNumber: val
});
}
updateInputMessage(evt) {
const val = evt.target.value;
this.setState({
inputMessage: val
});
}
From this code, I expect that it will receive 2 values from my inputs and output them to the console ONLY after clicking the button. But instead, for some reason, my code launches the getAccountInfo function twice after any change in the values of my inputs. Moreover, when the button is pressed, the function is not invoked at all.
>Solution :
You are invoking the function getAccountInfo() (with brackets) when passing it to onClick. You should just pass it without the brackets. To access the state value, you don’t need to pass them as arguments. Just read this.state in the function body. See modified code
class SideMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
inputNumber: '',
inputMessage: ''
};
this.getAccountInfo = this.getAccountInfo.bind(this)
}
getAccountInfo() {
console.log(this.state.inputNumber, this.state.inputMessage)
};
render() {
return(
<body className='SideMenuBg'>
<div className='SideMenu'>
<frame className='sideMenuBackgroundFrame'>
<input type='text' value={this.state.inputNumber} onChange={this.updateInputNumber} placeholder='Number'/>
<input type='text' value={this.state.inputMessage} onChange={this.updateInputMessage} placeholder='Message'/>
<button onClick={this.getAccountInfo}>press me</button>
</frame>
</div>
</body>
)
}
updateInputNumber(evt) {
const val = evt.target.value;
this.setState({
inputNumber: val
});
}
updateInputMessage(evt) {
const val = evt.target.value;
this.setState({
inputMessage: val
});
}