Is it possible to make this html table re-usable? I use the same table in 2 places and am using props dependant on its use. There is 1 thing I can't work out. Each instance of the table uses an onclickhandler with a parameter, 1 to delete the user (user.id) and the other to add the user (user), so each onClick takes different arguments.
example of 1 of the onClickHandler's
const onClickHandler = (user) => {
setAddedAlert(true);
removeAlert()
setFavourites([...favourites, user]);
};
example of the table being used in a component and props passed
{usersData &&
<Table
data={usersData}
onClickHandler={onClickHandler}
buttonText={"Add"}
/>
}
</div>
example of table
const Table = ({ data, onClickHandler, buttonText }) => (
<Container>
<StyledTable>
<THead>
<TR>
<TH>ID</TH>
<TH>NAME</TH>
<TH>PHONE</TH>
</TR>
</THead>
<TBody>
{data?.map((user) => (
<TR key={user.id} >
<TD>{user.id}</TD>
<TD>{user.name}</TD>
<TD>{user.phone}</TD>
<TD>
<Button
onClick={() => onClickHandler(user)}
>
{buttonText}
</Button>
</TD>
</TR>
))}
</TBody>
</StyledTable>
</Container>
)
export default Table;
CodePudding user response:
Separate function for add and remove would do the job.
function App() {
const data = [
{ id: 1, name: "Jay", phone: "1111111111" },
{ id: 2, name: "Mike", phone: "2222222222" },
{ id: 3, name: "Bob", phone: "3333333333" },
];
const [userData] = useState(data);
const [faveUsers, setFaveUsers] = useState([]);
const onClickHandleAdd = (user) => {
const newFaveUsers = [...faveUsers, user];
setFaveUsers(newFaveUsers);
};
const onClickHandleRemove = (user) => {
const newFaveUsers = faveUsers.filter((u) => u.id !== user.id);
setFaveUsers(newFaveUsers);
};
return (
<>
<Table
data={userData}
onClickHandler={onClickHandleAdd}
buttonText="Add"
/>
<Table
data={faveUsers}
onClickHandler={onClickHandleRemove}
buttonText="Remove"
/>
</>
);
}