2

How to add target='_blank' in navigate?

import { useNavigate } from 'react-router-dom';

const navigate = useNavigate();

navigate(`/record`, {
      state: {
        eventId: event.id,
      }
    });

2 Answers 2

5

The navigate function isn't capable of doing this, it can only navigate within the app in the same window/tab.

You can use the following:

  • Link passing a target="_blank" prop.

    <Link to="/record" target="_blank">
      /record
    </Link>
    
  • Anchor tag using a target="_blank" attribute.

    <a href="/record" target="_blank">
      /record
    </a>
    
  • window.open in a callback.

    const navigateOutApp = () => window.open("/record", "_blank", "noreferrer");
    
    ...
    
    <button type="button" onClick={navigateOutApp}>
      /record
    </button>
    
  • If you need to also pass "state" then you will need to temporarily store it in localStorage and retrieve it when the app and target component mount.

    const navigateExternal = (target, options) => {
      if (options.state) {
        localStorage.setItem("state", JSON.stringify(options.state));
      }
      window.open(target, "_blank", "noreferrer");
    };
    
    const Bar = () => {
      const [state, setState] = useState(JSON.parse(localStorage.getItem("state")));
    
      const location = useLocation();
    
      useEffect(() => {
        localStorage.removeItem("state");
      }, []);
    
      useEffect(() => {
        if (location.state) {
          setState(location.state);
        }
      }, [location]);
    
      useEffect(() => {
        console.log("Passed state", { state });
      }, [state]);
    
      return (
        <>
          <h1>Bar</h1>
          <div>State: {JSON.stringify(state)}</div>
        </>
      );
    };
    

Demo

Edit react-router-6-navigate-to-new-tab-with-state

Sign up to request clarification or add additional context in comments.

2 Comments

then I can't pass state to a new tab?
@VinceFrost Ah, sorry, missed that bit. For that you'll need to store what you want to pass in "state" in localStorage to be retrieved in the new browser context. I've updated my sandbox with internal/external examples with passing state.
0

Hello You can use a simple approach for this

<Link to="/yourRoute" target="_blank">
    Take me to other page
</Link>

According to react-router-dom the <a> tag is replaced by <Link> tag so you can use all <a> tag attributes on Link tag.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.