I have developed the code for the modal in React. I wanted to make a generic modal for the application and I came up with a solution but god knows how. Can anyone take a look at the code and explain why is it working and how can we make it better?
I’m writting the code snippet in Stackoverflow for the first time and I’m getting error in the react code. Could anyone please see what is the issue.
const {useState} = React;
//this variable is getting assigned the resolve function of a Promise.
// If the variable is defined inside the App() component then it does not work and throws undefined
// can anyone explain how this is working.
let resolveHelper;
const App = ()=> {
const [data, setData] = useState(["Apple", "Banana", "berries", "Kiwi"]);
const [isModalHidden, setIsModalHidden] = useState(false);
const handleDelete = async (fru) => {
try {
const res = await handlePromise();
if (res) {
// Delete Logic will come here
console.log("We will delete you");
} else {
// No is clicked escape logic will come here
console.log("you can go");
}
} catch (err) {
console.log(err);
}
};
// This function is returning a promise and assigning resolve function to a variable
const handlePromise = () => {
setIsModalHidden((prev) => !prev);
return new Promise((resolve) => {
resolveHelper = resolve;
});
};
// This function is listening to the button click of Modal
const handleConfirmation = (confirmation) => {
return new Promise((resolve, reject) => {
if (confirmation) resolveHelper(true);
else resolveHelper(false);
});
};
// Mapping the data to HTML
const dataContent = data.map((fruit) => (
<li key={fruit}>
{fruit} <button onClick={() => handleDelete(fruit)}>delete</button>
</li>
));
// Modal show or hide based on the flag value
const displayValue = isModalHidden ? "block" : "none";
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<ul>{dataContent}</ul>
<div style={{display:`${displayValue}`}}>
Are you sure you want to delete this
<button onClick={() => handleConfirmation(true)}> Yes</button>
<button onClick={() => handleConfirmation(false)}> No </button>
</div>
</div>
);
}
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App/>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>