Reputation: 57
I have a requirement to be implemented where- when the form is loaded, basis one of the attribute which contains a url link - a new browser tab should be auto opened with that url when form is loaded.
So i checked few stakc overflow links and found one solution Maintaining href "open in new tab" with an onClick handler in React
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
return (
<ul>
{dataset.map((x, id) => (
<li
key={id}
>
<b>{x.split('~')[0]}</b> - {checkString(x.split('~')[1])}
{x.split('~')[0]==='PAGE_URL' ?
openInNewTab(x.split('~')[1])
:
<></>
}
</li>
))}
</ul>
);
So with above code, when my form is loaded, it immediately loads new tab on broswer as expected but the issue here is whenever i try to type in other form questions or click on any button like radio button on that form, everytime it is opening new tab which i don't want. How do i prevent multiple times auto pop up of new tab or is there any other solution? Please help with solution or alternatives.
I mentioned whever i tried in above
Upvotes: 0
Views: 1043
Reputation: 437
You can call the openInNewTab
function from a useEffect hook. The reason a new tab is opened when ever you type in something in the input field is because react is re-rendering that component due to state changes. Since you want this function to be called only once, you can move the logic of calling this function to a useEffect hook.
Upvotes: 0