Reputation: 1371
I have a table in ReactJS that is displaying data from a database using the map function. It works like so:
displayData(){
return this.state.legoParts.map((legoPart) => (
<tr key={legoPart.id} onClick={() => this.showForm(legoPart)}>
<td>
{legoPart.piece}
</td>
<td>
{legoPart.type}
</td>
</tr>
)
)
}
However I want a form, using the same data as the table row, to appear when the row is clicked so that I can then use the form to update the data. I honestly have no idea how to go about this- I'm not sure if I should put the form in the table and have it display when clicked or something else. Any help would be appreciated!
Upvotes: 1
Views: 3275
Reputation: 35
First : Set Up the State to Manage the Selected Row
To store which row (or legoPart) was clicked you can use a state variable to
hold the currently selected legoPart so that you can display a form with its
details.
Secondly : Show form when row was clicked
Update the state when the row (or legoPart) was clicked .
Here is the code to do this
const [legoParts, setLegoParts] = useState([
{ id: 1, piece: 'Brick 2x4', type: 'Standard' },
{ id: 2, piece: 'Plate 1x2', type: 'Standard' },
]);
const [selectedPart, setSelectedPart] = useState(null);
const showForm = (legoPart) => {
setSelectedPart(legoPart);
};
const handleFormChange = (e) => {
const { name, value } = e.target;
setSelectedPart({ ...selectedPart, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Updated part:', selectedPart);
setSelectedPart(null); // Clear form after submission
};
Upvotes: 0
Reputation: 166
You'll need your app state to keep track of the part you're editing, and while you are rendering the table, decide whether to render a table row or the form based on that app state. I've put an example here: https://codesandbox.io/s/624p7zpzww
Upvotes: 1