nextui-org / nextui

🚀 Beautiful, fast and modern React UI library.
https://nextui.org
MIT License
20.44k stars 1.23k forks source link

How to create a dynamically changing table using NextUI? #2193

Open sgoldcreatives opened 6 months ago

sgoldcreatives commented 6 months ago

Discussed in https://github.com/nextui-org/nextui/discussions/2192

Originally posted by **sgoldcreatives** January 1, 2024 So I have no problem displaying the table using arrays and such. My problem is that I have a user input `weight` that I want to affect a table item `dosage` the problem is that I think that NextUI only renders the table once, therefore if `weight` changes after runtime, it does not affect `dosage`. ``` //..in data.ts export const columns = [ { uid: "name", name: "NAME", }, { uid: "dosage", name: "DOSAGE", }, { uid: "tags", name: "TAGS", }, { uid: "dosageForm", name: "DOSAGE FORM", }, ]; export type medForm = "Oral" | "Injectable"; export type medTags = | "For Dogs" | "For Cats" | "Sx" | "Tx" | "Pain" | "Antibiotic" | "Steroid"; export const medications: Med[] = [ { id: 1, dosage: 0.03, name: "Meloxicam", tags: ["For Dogs", "For Cats", "Pain", "Sx"], dosageForm: "Oral", }, ... etc //.. in page.tsx 'use client' //imports.. type User = (typeof medications)[0]; export default function Home() { const renderCell = React.useCallback( (user: User, columnKey: React.Key) => { const cellValue = user[columnKey as keyof User]; switch (columnKey) { case "name": return (

{cellValue}

); case "dosage": return (

{Number(cellValue) * Number(weight)} // should change dynamically, if I hardcode weight to 5 for example, dosage will stay cellValue * 5

); } }, [weight] ); return ( {(column) => ( {column.name} )} {(item) => ( {(columnKey) => ( {renderCell(item, columnKey)} )} )}
) } ```
cdx111 commented 6 months ago

no way

pkail commented 6 months ago

Another (related) issue is that if the user sorts the table and then moves away from the page, when he goes back the table will be unsorted. It would be great if we could have a way to trigger sorting programmatically.

edgeboy47 commented 2 months ago

For anyone that sees this, I had a similar issue and solved it by setting a key attribute on the Table component. Whenever that key changes, it causes the Table component to re-render

rnithin133 commented 1 month ago

Hi @edgeboy47 , I tried that but not working. @edgeboy47 can show me some code!!

agsafronenko commented 1 month ago

For anyone that sees this, I had a similar issue and solved it by setting a key attribute on the Table component. Whenever that key changes, it causes the Table component to re-render

Thank you, worked for me!

jimmyzzxhlh commented 1 month ago

Changing the key as suggested by @edgeboy47 works, but this is pretty hacky.

My use case is to dynamically change some components in a table in Edit mode, i.e. if I want to edit a row inline in the table, then I can click on an edit button and then the cells of that row will become editable.