Reputation: 729
I'd like to open a materialui dialog and handle the result from javascript to make a simple Yes/no prompt.
Id like it to work something like this (just mockup code to explain)
<MyPromptComponent />
{
MyPromptComponent.show('Do you really want to?').then((result) => alert(result ? 'then do it' : 'walk away') );
}
So the question is; How (if) can I put functions in my component, that I can call from a reference?
If someone knows of an example where something similar is dont I'd appreciate it.
Edit : 11/10/2020 The "problem" with the state way of doing this is that I have to leave the function showing the prompt, having to store temporary variables outside the function. If I could do something like this the code would be much more readable:
{
let tempData = doAProcessForThisFunctionOnly();
let sureResult = confirmDialog.show('Are you sure?');
if(sureResult )
doSomeMoreWithTempData(tempData);
else
doSomeOtherStuff(tempData);
doSomeEndStuff(tempdata);
}
In react I have to do this
{
let tempData = doAProcessForThisFunctionOnly();
tempDataRef.current = tempData;
setShowDialog();
}
onYes = () => {
let workData = tempDataRef.current;
doSomeMoreWithTempData(workData );
doSomeEndStuff(workData)
}
onNo = () => {
let workData = tempDataRef.current;
doSomeOtherStuff(workData );
doSomeEndStuff(workData)
}
doSomeEndStuff = (workData) => {
//Do the stuff here
}
It really seems I need to jump in and out of a lot of functions just to get a simple confirmation and even using variables outside the functon (refs). That really seems a big step backwards code-wise, to me.
The "vanilla" way of doing this would even let me use the same prompt-dialog component from many different functions. In reactit seems I need a separate confirm-dialog for each case as the "yes"/"no" events are hardcoded per case.
Upvotes: 2
Views: 56
Reputation: 5524
You should control everything with state:
export default function App() {
const [show, setShow] = useState(false);
return (
<div className="App">
<button onClick={() => setShow(true)}>Initiate</button>
<MyPromptComponent
title="Do you really want to?"
show={show}
onConfirm={() => {
setShow(false);
alert("Then do it")
}}
onCancel={() => {
setShow(false);
alert("Walk away")
}}
/>
</div>
);
}
const MyPromptComponent = ({ show, title, onConfirm, onCancel }) => {
return (
<React.Fragment>
{show &&
<div>
Lets pretend this is modal - {title}
<button onClick={() => onConfirm()}>Confirm</button>
<button onClick={() => onCancel()}>Cancel</button>
</div>
}
</React.Fragment>
);
};
Please see sandbox
Upvotes: 1