Reputation: 97
I'm using a custom hook to display modal window, do you know how can I display the modal window once, right now when I refresh the window I can see again the modal window...
What approach will be the best?
This is my code:
import React from "react";
import useModal from "./customHooks/useModal";
import Modal from "./customHooks/Modal";
const SearchPage = ({ location }) => {
const { isShowing, toggle } = useModal();
const search = window.location.search;
const parametros = "?q=Search";
window.addEventListener('popstate', (event) => {
console.log('Event', event);
});
return (
<>
<p>
<strong>Location Props: </strong>
{location.search}
</p>
{parametros === search ? (
<Modal
width={["333px", "111px"]}
height={["555px", "444px"]}
margin={["0px 10px 3px 5px", "1px 2px 3px 4px"]}
padding={["0px 11px 4px 7px", "1px 2px 3px 4px"]}
isShowing={!isShowing}
hide={toggle}
contentModal={"OK Modal"}
/>
) : (
<Modal
width={["333px", "111px"]}
height={["555px", "444px"]}
margin={["0px 10px 3px 5px", "1px 2px 3px 4px"]}
padding={["0px 11px 4px 7px", "1px 2px 3px 4px"]}
isShowing={!isShowing}
hide={toggle}
contentModal={"Error Modal"}
/>
)}
<button className="button-default" onClick={toggle}>
Show Modal
</button>
</>
);
};
export default SearchPage;
Thank you and Regards,
Upvotes: 1
Views: 1644
Reputation: 54
You can manage a state with localStorage.
When a modal activate, set a value to localStorage.
+)
const SearchPage = ({ location }) => {
const { isShowing, toggle } = useModal();
console.log("LOCATION", location);
const search = window.location.search;
console.log("SEARCH", search);
const params = new URLSearchParams(search);
console.log("PARAMS", params);
const foo = params.get("bar");
console.log("foo", foo);
const parametros = "?q=Search";
window.addEventListener('popstate', (event) => {
console.log('Event', event);
});
// create a click method check if a value in localStorage
const handleClick = () => {
const flag = localStorage.getItem('flag');
if (!flag) {
localStorage.setItem('flag', true);
toggle();
}
}
return (
<>
<p>
<strong>Location Props: </strong>
{location.search}
</p>
{parametros === search ? (
<Modal
width={["333px", "111px"]}
height={["555px", "444px"]}
margin={["0px 10px 3px 5px", "1px 2px 3px 4px"]}
padding={["0px 11px 4px 7px", "1px 2px 3px 4px"]}
isShowing={!isShowing}
hide={toggle}
contentModal={"OK Modal"}
/>
) : (
<Modal
width={["333px", "111px"]}
height={["555px", "444px"]}
margin={["0px 10px 3px 5px", "1px 2px 3px 4px"]}
padding={["0px 11px 4px 7px", "1px 2px 3px 4px"]}
isShowing={!isShowing}
hide={toggle}
contentModal={"Error Modal"}
/>
)}
// change toggle function to we created handleClick functtion as above.
<button className="button-default" onClick={handleClick}>
Show Modal
</button>
</>
);
};
export default SearchPage;
Upvotes: 1