Ask Your Question
1

How can I make React open a new tab only once?

asked 2022-05-06 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-08-18 02:00:00 +0000

qstack gravatar image

You can use the useEffect hook to check whether the component has already mounted and then use window.open() to open a new tab only if the component is mounted for the first time. Here's an example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    const isOpened = localStorage.getItem('isOpened');
    if (!isOpened) {
      window.open('https://www.example.com', '_blank');
      localStorage.setItem('isOpened', true);
    }
  }, []);

  return <div>Hello world!</div>;
}

export default MyComponent;

In this example, we're using localStorage to store a flag (isOpened) that indicates whether the new tab has been opened before. By default, isOpened is null, so on the first mount of the component, the new tab will be opened and isOpened will be set to true. On subsequent mounts, isOpened will have a value of true, so the new tab won't be opened again.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-06 11:00:00 +0000

Seen: 12 times

Last updated: Aug 18 '21