I have a react component called App that contains 2 components: Form and Table. And both of them are controlled component.
In the form, there is an input element and a button.
The input element has an onChange attribute; whenever the value changes it changes the value in the App's state.
The button has an onClick attribute that is provided by the App component; Whenever the button is clicked, the state's firstNames (which is an array) will be added with the state value of firstname.
The problem is when I clicked the button, it will throw an error saying that I didn't pass in an array and that it doesn't have a map method, even though in the call back, the updated state does show an array.
Below is the code:
function Form(props) {
return (
<form>
<label>
Item: <input value={props.value} onChange={props.handleChange} />
</label>
<button onClick={props.handleClick}>Submit</button>
</form>
);
}
function Table(props) {
let firstNames = props.names.map((item, index) => {
return (
<tr key={index}>
<td>{item}</td>
</tr>
);
});
return (
<table>
<thead>
<tr>
<th>First Name</th>
</tr>
</thead>
<tbody>{firstNames}</tbody>
</table>
);
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputField: "",
firstNames: ["Joey", "Chloe"],
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(event) {
this.setState({ inputField: event.target.value });
}
handleClick() {
this.setState(
{
firstNames: this.state.firstNames.push(this.state.inputField),
},
console.log(this.state.firstNames)
);
}
render() {
return (
<div>
<Form
value={this.state.inputField}
handleChange={this.handleChange}
handleClick={this.handleClick}
/>
<Table names={this.state.firstNames} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));