I have a main component, App(). I have another component, Event(). Event has a dialog, defined in a separate file, that opens and populates from a click on a table row. In that case, the data in the dialog can be modified and saved to a database.
Now the second case is to create a new event. The Add button for that is in another component. When clicked, I want Event to open its dialog, un-populated.
I’ve seen many similar examples but I can’t get them to work for my use case. I think I need to useContext but I don’t get how to apply it. Here’s some code to clarify:
index.tsx
ReactDOM.createRoot(document.getElementById("root")!).render(
<App/>
);
App.tsx
const App = () => {
return (
<Router>
<MainAppBar isAppSidebarOpen={false} />
</Router>
);
};
The router goes to Event page from menu click in MainAppBar. A click on a table row opens and populates a MUI dialog. It will open just by setting the open property to true.
event.tsx
function handleRowClick(event: React.MouseEvent<unknown>, id: number) {
const selectedRowData = getSelectedRowData(id);
setDialogData(selectedRowData);
setOpen(true);
}
Now I need to open the same dialog, unpopulated, on a button click in the App component.
function ClickAddIconComponent(props: { key: string }) {
return (
<Fab size="small" color="primary" aria-label="add" onClick={handleAddIconClick} sx={{ marginTop: "6px", textAlign: "right"}}>
<AddIcon />
</Fab>
)
}
}
function handleAddIconClick() {
<TellEventPageToOpenDialog message="openEmptyDialog" />;
}
I’m assuming I need to useContext() to open Event’s dialog?
interface MessageContextType {
message: string;
setMessage: React.Dispatch<React.SetStateAction<string>>;
}
const MessageContext = React.createContext<MessageContextType | null>(null);
const TellEventPageToOpenDialog = (props:any) => {
const [message, setMessage] = React.useState(props.message);
return (
<MessageContext.Provider value={{ message, setMessage }}>
<EventPage />
</MessageContext.Provider>
);
}
Now how do I get Event receive the message and open its dialog? Am I going about this wrong?