I am trying to create a modal that will have a + / - counter.
However, I think since the state is in base component, modal is not able to recognize it. Any idea how to solve it?
I tried passing it as a prop but no luck
export default function ProgramCard() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
console.log(1)
setCount(prevCount => prevCount + 1);
};
const handleDecrement = () => {
setCount(prevCount => prevCount - 1);
};
const [opened, { open, close }] = useDisclosure(false);
const openModal = () => modals.openConfirmModal({
title: 'Input Data',
children: (
{" # "}{count}{" # "}
),
labels: { confirm: 'Confirm', cancel: 'Cancel' },
onCancel: () => console.log('Cancel'),
onConfirm: () => notifications.show({
title: 'Input Submitted',
message: 'Complete',
}),
});
return (
Sample
)
}
I tried passing it as a prop but no luck
Tuhin PaulPosted Mar 26, 2023, 3:10 AM
This is the more optimized version of my previous code:
And this is the code for ConfirmModal component:
Tuhin PaulPosted Mar 26, 2023, 3:09 AM
Also you can improve the code by separating the modal into a separate component .i.e., instead of having the modal JSX code inside the openModal function, you can create a separate component for the modal and pass the necessary props to it. Also use useCallback hook for event handlers. In the current code, the handleIncrement and handleDecrement functions are recreated on every render. You can use the useCallback hook to memoize these functions and prevent unnecessary renders.Also instead of accessing the open and close functions using array syntax, you can use object destructuring to make the code more readable.
Tuhin PaulPosted Mar 26, 2023, 3:06 AM
Check the code:
Tuhin PaulPosted Mar 26, 2023, 3:06 AM
Hello,
You can pass the
countstate and its setter function as props to the modal component, so that the modal can access and update the state.