I have a dynamic table
in my app and I get its data from an api, I need to get on of its parameters and add some others then post it to another api.
and here is my code
:
edit = (data) => {
console.log()
}
return (
<div className="App">
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="customized table">
<TableHead>
<TableRow>
<TableCell>Horse Name(ENG)</TableCell>
<TableCell>Owner</TableCell>
<TableCell>Microchip id</TableCell>
<TableCell>Number</TableCell>
<TableCell>Round</TableCell>
</TableRow>
</TableHead>
<TableBody>
{product
.filter((item) => {
if (search == []) {
return item;
}
})
.map((item) => {
return (
<TableRow key={item.id}>
<TableCell component="th" scope="row">
{item.nameEn}
</TableCell>
<TableCell component="th" scope="row">
{item.owner}
</TableCell>
<TableCell component="th" scope="row">
{item.chipNumber}
</TableCell>
<TableCell component="th" scope="row">
<TextField label="number" variant="standard" />
</TableCell>
<TableCell component="th" scope="row">
<TextField label="Round" variant="standard" />
</TableCell>
<TableCell component="th" scope="row">
<Button variant="primary"
value={loading ? 'Loading...' : 'Publish'}
onClick={() => edit(item)}
// onClick={handleAdd}
disabled={loading}>Add to round</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
The problem is I don't know how to pass the row data from table to edit
as a string, I want when I call edit function, it prints the one of the parameters on the row
this helped me a little but I don't know why it doesn't work well and it doesn't recognize data
as a function
. I am really a newbie sorry if it has an obvious problem!
CodePudding user response:
You almost implemented it, but your edit function was not defined properly.
function SampleComponent () {
// rest of the codes ...
const addToRoundHandler = (selectedItem) => {
console.log(selectedItem) // ---> print your selected item object!
console.log(`Item name : ${selectedItem.nameEn} and the owner ${selectedItem.owner}`)
// you might need to call an API to send the selected item to the server
}
return (
// rest of the codes ...
<TableCell component="th" scope="row">
<Button
variant="primary"
value={loading ? 'Loading...' : 'Publish'}
onClick={() => addToRoundHandler(item)} // ---> here
disabled={loading}
>
Add to round
</Button>
</TableCell>
// rest of the codes ...
)
}
Pay attention to the comments on the codes. I use some meaningful names to better explain, you can change them.
if you want to show the selected item on the page, you need to create a state variable:
function SampleComponent () {
const [currentItem, setCurrentItem] = useState({})
// rest of the codes ...
const addToRoundHandler = (selectedItem) => {
console.log(selecteItem);
setCurrentItem(currentItem)
}
// rest of the codes ...
return (
// rest of the codes ...
<div>
{
currentItem.length > 0 && <p> You selected: {currentItem.name} </p>
}
</div>
// rest of the codes ...
)
}