You can trigger the Add Row action of Material Table from an external button by using a ref and overriding the components.Action prop.
Here’s a clean working example:
---
Step-by-Step:
1. Create a useRef() to hold a reference to the Add action.
2. Override components.Action to capture the Add button when its tooltip is 'Add'.
3. Use an external button to trigger .click() on that ref.
---
Full Working Code:
import React, { useRef } from "react";
import MaterialTable, { MTableAction } from "material-table";
import { Button } from "@material-ui/core";
const MyTable = () => {
const addActionRef = useRef();
const columns = [
{ title: "Name", field: "name" },
{ title: "Age", field: "age", type: "numeric" },
];
const [data, setData] = React.useState([]);
return (
<div>
<Button
color="primary"
variant="contained"
onClick={() => addActionRef.current.click()}
>
Add New Item
</Button>
<MaterialTable
title="My Table"
columns={columns}
data={data}
editable={{
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
setData([...data, newData]);
resolve();
}, 600);
}),
}}
components={{
Action: (props) => {
if (
typeof props.action === "function" ||
props.action.tooltip !== "Add"
) {
return <MTableAction {...props} />;
} else {
return (
<div
ref={addActionRef}
onClick={props.action.onClick}
style={{ display: "none" }}
/>
);
}
},
}}
/>
</div>
);
};
export default MyTable;
---
Explanation:
useRef() holds a reference to the Material Table’s internal Add action.
Inside components.Action, when the tooltip is 'Add', attach the ref to a hidden <div> which triggers props.action.onClick.
The external button calls addActionRef.current.click() to open the add row dialog.
---
Result:
You now have an external button that can trigger the Add Row functionality of your Material Table.
---
Hope this helps!
---
Tags: reactjs material-table material-ui ref external-actions
---
Would you like me to suggest a title for your answer too?