How to use preventDefault function in useRef (reactjs + nodejs) - javascript

This is my function to download zip file
autoDownload.current.click() - automatically click on HTML element which download my zip file.
But Problem is page used to reload while this process.
How i can prevent my page to reload.
const downloadZipFile = () => {
console.log('download');
autoDownload.current.click();
}
I need something like this.
const downloadZipFile = () => {
console.log('download');
autoDownload.current.click((e) => {
e.preventDefalut();
});
}

Have you tried adding an 'onClick' property to the link/button with a function that includes the e.preventDefault() ? Not sure exactly how you're setting this up, but below has some ideas (using reactjs).
const downloadZipFile = (e) => {
e.preventDefault()
// Add your download zip functionality here
}
// Example of function that will execute on page load
React.useEffect(() => {
downloadZipFile()
}, [])
return (
<Button id='someid' onClick={downloadZipFile} />
)

Related

addEventListener won't be triggered at the first click

I'm trying to load a js script when a button(in a React component) is clicked.
I use webpack import to load the JS file.
Not sure how come the addEventListener won't be triggered at the first click.
I add cosole.log for debugging. when clicking that button first time, will only get TEST_1.
And, if click that button second time, will get TEST_2 and TEST_3 as well.
React Component snippet
const Component = () => {
const loadJS = () => import(/* webpackChunkName: "od-survey" */ "./ol_od_survey.js");
return (
<>
<button
className={"button"}
onClick={loadJS}
>
Click Me
</button>
</>
);
};
export default Component;
JS file snippet
function(w, o) {
"use strict";
console.log("TEST_1");
w.addEventListener("click", function(event) {
console.log("TEST_2");
if ( event.target.textContent === "Click Me") {
console.log("TEST_3");
actionFunc();
}
});
var actionFunc = function() {
Do Someting Here
}
})(window, window.OOo);
Click the button to load that JS file
As discussed in the comments the reason why you need 2 click, because you are attaching your "loaded" eventListener within the first click, so it just cannot be triggered, only subsequent clicks will trigger that listenet.
Also, as discussed if what you need is to execute actionFunc() first time when script isn't loaded yet then you could just execute it manually on script load by adding call to actionFunc() at script end
function(w, o) {
"use strict";
console.log("TEST_1");
w.addEventListener("click", function(event) {
console.log("TEST_2");
if ( event.target.textContent === "Click Me") {
console.log("TEST_3");
actionFunc();
}
});
var actionFunc = function() {
Do Someting Here
}
//manually execute actionFunc on first load
actionFunc();
})(window, window.OOo);
Other "hacky" way would be to use ref on button and trigger click on it after import finished import(/* webpackChunkName: "od-survey" */ "./ol_od_survey.js").then(_ => btnRef.current.click());

Page Leave Confirmation using React

I'm currently working on a project where I want to show a custom Dialogue box with my Own Content ("Save your data into drafts before leaving"). I have tried different methods but can't find a proper way to do it. I explore all the previous questions on StackOverflow but they didn't work properly in my case.
useEffect(() => {
return () => {
window.onbeforeunload = function() {
return "do you want save your data into drafts before leave?";
};
}
},[])
Currently, I've written the above code in Plain JavaScript to do, but it's just showing the dialogue box on tab close and reload while not showing on custom click events to navigate to other pages or window back button.
React can't help me in this because they remove useBlocker, usePrompt from new releases. How can I achieve it?
One way of doing this is :
import { Prompt } from 'react-router'
const MyComponent = () => (
<>
<Prompt
when={shouldBlockNavigation}
message='Do you want ot save data before leave?'
/>
{/* Component JSX */}
</>
)
If wants on page refresh or browser closing then add:
useEffect(() => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = undefined
}
},[]);
Second way is to use history if using react-router
useEffect(() => {
let unblock = history.block((tx) => {
// Navigation was blocked! Let's show a confirmation dialog
// so the user can decide if they actually want to navigate
// away and discard changes they've made in the current page.
let url = tx.location.pathname;
if (window.confirm(`Are you sure you want leave the page without saving?`)) {
// Unblock the navigation.
unblock();
// Retry the transition.
tx.retry();
}
})
},[]);
useEffect(() => {
const unloadCallback = (event) => {
event.preventDefault();
event.returnValue = "";
return "";
};
window.addEventListener("beforeunload", unloadCallback);
return () => {
window.addEventListener("popstate", confirmation());
window.removeEventListener("beforeunload", unloadCallback);
}
}, []);
I just did it with this code sample (actually I combine two events to show dialogue whenever users leave a page) and it's working fine for me. Thanks to all of you guys ... Especially #DrewReese for the help

CKEditor 5 Insert text on button click - Pure JS

I'm trying to create a sort of dropdown menu that a user can insert tokens into a CKEditor with. I've found that I can insert text in an editor with this code:
editorInstance.model.change( writer => {
let pos = editorInstance.model.document.selection.getFirstPosition();
writer.insertText( "TEST", pos,0);
});
It works when I put it in the ClassicEditor.create.then for testing but it does nothing when I place this in a $().click event. I can log something from inside the callback so I know the code is executed but nothing is inserted.
I've been trying to get this working for hours now but all the examples I can find is in angular or any other frameworks.
I Solved the issue you faced as follows
first defined new editor that is null and Then instatiate Ckeditor 5
let neditor = null;
ClassicEditor.create(document.querySelector('#editor'))
.then(editor => {
neditor = editor;
})
.catch(error => {
console.error(error);
});
using pure js
document.addEventListener("click", (event) => {
var button = event.target;
if (event.target.type === 'button' && event.target.className.includes('testtokenbutton')) {
neditor.model.change(writer => {
const insertPosition = neditor.model.document.selection.getFirstPosition();
writer.insertText(button.id, insertPosition);
});
}
});

Only show Popup one time with React (local storage)

I would like to show the popup only one time with React Hooks.
Access for the first time to example.com/campaign/1234
Show popup
Close or refresh the page.
Access again to example.com/campaign/1234 and don't show popup
Access for the first time to example.com/campaign/0000 (is a different URL)
Show popup
Close or refresh the page
Access again to example.com/campaign/0000 or example.com/campaign/1234 and the popup is not being displayed
Any idea of how to do it? I know that I need to use local storage but how can I trigger the event when the user closes or refreshes the page?
Here is a sandbox.
I also read this thread but it doesn't mention how to do it with Hooks
If you never use the setStickyState callback from the custom hook, the state will just remain at its initial value.
It seems like setStickyState also has a bug in it, where it won't update if the key has changed. Here's an enhanced version that I've called useLocalStorage, which should work more reliably:
export function useLocalStorage(key, initialDefault) {
const [val, setVal] = useState(() => {
const localStorageVal = localStorage.getItem(key);
return localStorageVal !== null
? JSON.parse(localStorageVal)
: initialDefault;
});
useEffect(() => {
if (localStorage.getItem(key) === null) {
setVal(initialDefault);
}
}, [key, initialDefault]);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(val));
}, [val, key]);
return [val, setVal];
}
You can then use it like this:
const [visited, setVisited] = useLocalStorage(pageId, false);
const navigateAway = useCallback(() => {
setVisited(true)
}, [setVisited])
useEffect(() => {
// if user navigates away to a completely different site
// or refreshes the page etc
window.addEventListener("beforeunload", navigateAway);
// if user navigates to another page on the same site
return () => {
navigateAway();
window.removeEventListener("beforeunload", navigateAway);
};
}, [pageId, navigateAway]);
// ...
<dialog open={!visited}>
<p>Welcome to page {pageId}!</p>
<button onClick={() => setVisited(true)}>
Don't show again on this page
</button>
</dialog>
Here's a demo (with TypeScript):
useLocalStorage demo

react js : detect page refresh

I am new to react.js.
I have a simple page with table. When I reload the page, state is getting lost.
Is there a way to detect the browser refresh ?
The event beforeunload is executed just before window browser is being refreshed. Event is cancellable.
window.beforeunload = (e) => {
console.log('Stop this');
e.preventDefault()
e.returnValue = '';
};
When using React an option is to take control in your Application component, or your most higher order component, in the componentDidMount lifecycle method as #georgim suggested instead componentWillUnmount as I first suggested, and manage there what you want to achieve.
With [react-beforeunload][1] you can track the page changes easily
import { useBeforeunload } from 'react-beforeunload'
const App = () => {
const [preventMultiSubmit, setPreventMultiSubmit] = useState(false)
}
const pageRefConf = useBeforeunload((event) => {
if (preventMultiSubmit) {
event.preventDefault()
}
})
useEffect(() => {
window.addEventListener('beforeunload', pageRefConf)
return () => {
window.removeEventListener('beforeunload', pageRefConf)
}
}, [])
This worked for me. I hope this one will work for you too.
[1]: https://www.npmjs.com/package/react-beforeunload
Try this one. This worked for me.
if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}

Categories