I want to make table accordion .when I clicked on table row the next table data should display by default first one should be open and when I click another header there content should open without closing previous one.
I have created the state:
const [active, setActive] = useState(false);
const handleClick = () => {
setActive(!active);
};
return (
<div>
<div>
<table className="table border">
<tr>
<td colSpan={3} className="header" onClick={handleClick}>
Winfield
</td>
</tr>
{active && (
<tr>
<td>USJN - Tifton </td>
<td>12 </td>
<td> 800</td>
</tr>
)}
<tr>
<td colSpan={3} className="header" onClick={handleClick}>
Helena
</td>
</tr>
{active && (
<tr>
<td>USJN - Tifton USJN - Tifton USJN - Tifton USJN - Tifton </td>
<td>12 </td>
<td> 800</td>
</tr>
)}
</table>
</div>
</div>
);
2
Answers
There is plenty of ways doing this.
Typically, you will want to iterate over and array with the table data instead of creating each row manually.
Define an object with the data you need.
With this defined data, instead of creating each Table Row for yourself, iterate over this array creating them dinamically.
Set the tableData as the state and notice the active value (true for the first value in the array, false for the others). This will make your first row open by default.
Your onClick handler passes the id of the row that need to be changed the active state. we updated the state switching active for the id and let react take care of rerendering the component, since state has updated.
If you only will have two rows, you can go with
And have two states separate: one for each row. But it will be a nightmare if you need a more rows.
One way would be to extract the accordion row into it’s own separate component. This will allow you to have separates states for each row.