I have a component with a table that is loaded with the data sent by the REST API, my question more than anything, is if it is good to delete a row with remove () or deleteRow (index) entering the DOM or I have to manipulate the DOM through a state (useState) for good practice or something like that.
Additional info: I have gotten used to manipulating the DOM directly with pure javascript when making static web pages, but in React I think you have to use props, state, hooks to manipulate the DOM elements or am I wrong? there must be cases I guess.
DOM TRAVERSING
export default function App() {
const data = ['Eli','Smith', 'Jhon']
const handleDelete = (index,e) => {
//I can save an ID in <tr> through datasets (data-)
//to get it by traversing the DOM when the user clicks and delete it
//also in my database (API), that's Ok?
e.target.parentNode.parentNode.parentNode.deleteRow(index)
}
const rows = data.map((item, index) => {
return (
<tr key={index}>
<td>{item}</td>
<td><button onClick={e => handleDelete(index,e)}>Delete</button></td>
</tr>
)
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<table>
{rows}
</table>
</div>
);
}
That's OK ?
Or do I have to put the rows in a state (useState) and update it by removing the and re-rendering?
Best practice is to manage data through state, I would suggest not to do DOM manipulation manually
export default function App() {
const [data, setData] = useState(['Eli','Smith', 'Jhon']);
const handleDelete = (index,e) => {
setData(data.filter((v, i) => i !== index));
}
const rows = data.map((item, index) => {
return (
<tr key={index}>
<td>{item}</td>
<td><button onClick={e => handleDelete(index,e)}>Delete</button></td>
</tr>
)
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<table>
{rows}
</table>
</div>
);
}
use hook useState to save your data and after that with handlerDelete remove the element and set the data. React will re-render component (because your state has been changed) and you get necessary result: