I'm creating a form that displays its input on a table, and every time I click on submit, the 1st row is added and the second is added too but not on the table. I'm not sure what's the issue.I'm thinking it could be because of how I manipulated the arrays that store the states? if not, what could be?
Here is my code:
function Text(props) {
var style = {
paddingTop: 5,
margin: 5
};
return (
<div>
<div style={style}> {props.label} </div>
<input
type="text"
name={props.name}
style={style}
value={props.labelInputText}
onChange={props.changeHandler}
/>
</div>
);
}
function TableFormList(props) {
return(
<table>
<tr>
{props.headers.map((item,index) => <th key={index}>{item}</th>)}
</tr>
<tbody>
<tr>
{props.formElements.map((item,index) => <td key={index}>{item}</td> )}
</tr>
</tbody>
</table>
)
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
items: []
};
this.changeHandler = this.changeHandler.bind(this);
this.AddElementsOnSubmit = this.AddElementsOnSubmit.bind(this);
}
changeHandler(event) {
this.setState({ [event.target.name]: event.target.value });
}
AddElementsOnSubmit() {
var firstName = this.state.firstName;
var lastName = this.state.lastName;
var elements = this.state.items.slice();
elements.push(firstName, lastName);
this.setState({ items: elements, firstName: "", lastName: "" });
}
render() {
var style = {
padding: 5,
margin: 5
};
return (
<div>
<Text
label="First Name"
name="firstName"
labelInputText={this.state.firstName}
changeHandler={this.changeHandler}
/>
<Text
label="Last Name"
name="lastName"
labelInputText={this.state.lastName}
changeHandler={this.changeHandler}
/>
<input
type="submit"
value="submit"
style={style}
onClick={() => this.AddElementsOnSubmit()}
/>
<div>
<TableFormList
headers={["First Name", "Last Name"]}
formElements={this.state.items}
/>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
<tr>element instead of the<td>, that way for every item in your array, it creates a new row instead of just creating new cells.