Reputation: 4200
I have an application what takes the date from inputs and saving it, the data are apendded bellow, something like todo list. But now i have an issue trying to display the data, because i want to display it in a specific order as table row, but now the data is not showing properly, because i want to have Name under Name, Old under old, delete button under delete Text, ad edit button under edit text.
How to do this?
link to my application: https://codesandbox.io/s/nifty-moore-g86kd
Upvotes: 1
Views: 1037
Reputation: 1559
There are a few issues in your code.
import React, { useState, useEffect } from "react";
export default function App() {
const [user, setUser] = useState({
name: "",
old: ""
});
// A new state to keep track of the added users
const [users, setUsers] = useState([]);
const changeUser = e => {
const v = e.target.value;
setUser({
...user,
[e.target.name]: v
});
};
// On form submit, all you need to do is to update the users state
// Then render will take care of the rest
const submitForm = e => {
e.preventDefault();
setUsers([...users, user]);
};
// This is how in react we update the content
// Whenever, there is a change in state, this will get called and content will be updated
// Ps: It's being called in the render
const renderBody = () => {
const content = [];
users.map(item => {
content.push(
<tr>
<td>{item.name}</td>
<td>{item.old}</td>
<td>Delete btn</td>
<td>Edit btn</td>
</tr>
);
});
return content;
};
return (
<div className="to-do">
<form action="" onSubmit={submitForm}>
<label htmlFor="">
Name
<input
name="name"
onChange={changeUser}
value={user.name}
type="text"
/>
</label>
<label htmlFor="yes">
Old Yes
<input
id="yes"
name="old"
onChange={changeUser}
value="yes"
type="radio"
/>
</label>
<label htmlFor="no">
Old No
<input
id="no"
name="old"
onChange={changeUser}
value="no"
type="radio"
/>
</label>
<input value={user.old} type="submit" value="SUBMIT" />
</form>
<div className="res">
<table>
<tr>
<th>Name</th>
<th>OLD</th>
<th>DELETE</th>
<th>Edit</th>
</tr>
<tr id="res" />
{renderBody()}
</table>
</div>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
So what you need
Upvotes: 1