I am capturing the input value as a state and on button submit I want to add the result into an array.
The problem I am having is every time I type in a character in the input field it creates a new array before I even hit the submit button.
Following is the screenshot of the weird behaviour.
Here is my code:
import React, { Component } from "react";
import autoBind from "react-autobind";
let fixtures = [];
const submitFixture = (homeTeam, awayTeam) => {
fixtures.push({
homeTeam: homeTeam,
awayTeam: awayTeam
});
};
class CreateFixture extends Component {
constructor(props) {
super(props);
autoBind(this);
this.state = {
homeTeam: "",
awayTeam: ""
};
}
render() {
const { homeTeam, awayTeam } = this.state;
return (
<React.Fragment>
<p>Home Team</p>
<input
value={homeTeam}
onChange={e => {
this.setState({ homeTeam: e.target.value });
}}
/>
<p>Away Team</p>
<input
value={awayTeam}
onChange={e => {
this.setState({ awayTeam: e.target.value });
}}
/>
<button onClick={submitFixture(homeTeam, awayTeam)}>
Create fixture
</button>
{console.log(fixtures)}
</React.Fragment>
);
}
}
export default CreateFixture;
