How to access state passed through Link element when opening in a new tab?

Viewed 75

I am passing a state from Link element to another component, it works fine if I click on it, but if I try to open the link in a new tab, the state doesn't get passed. How can I fix this?

Code for reference:

<Link to={{pathname:"/open-page", state:{key: 'hello'}}}/>

openPage.js


import React, { useEffect, useRef } from 'react';
import { bool } from 'prop-types';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { createWidget } from '@typeform/embed';
import { injectIntl, intlShape } from '../../util/reactIntl';


export const OpenPageComponent = props => {
  const { intl, scrollingDisabled } = props;

  console.log('state', props.location.state.key);  //undefined on opening in a new tab
1 Answers

I think that this is because you are redirecting via a window object rather than react-router, a link is at its core a url redirect and you need to use history.push in react-router to persist the state and use it in the new window? Hopefully this is of some help:

https://reactrouter.com/web/api/history

this.props.history.push('/');

const LoginButton = ({ history }) => (
  <button onClick={() => { history.push('/login'); }} >
    Log in
  </button>
);

Related