I have a complex react component on my main page. I'm not using redux. On click of a button, I want to open the same instance of the react component with some new props in a new tab. The problem is I'm not sure how to keep them synchronized.
Let us say I have an array in the state of my component and I'm displaying the contents of the array in the component. Now based on the user's input, I will modify the array. I want the updated array to show up in the component which is opened in the new tab as well.
class App extends Component{
constructor(props){
this.state = {arr = []};
}
handleUserInput = arr => {
//make changes to arr
this.setState({ arr });
};
render(){
return(
// code to call this.handleUserInput()
<button href="/newtab" target="_blank"> </button>
{arr} //display the array here
.......
)
}
}
The scenario goes like this:
I'm using react routing like this:
const routing = (
<Router>
<Route exact path="/" component={App} /> //user inputs something on this instance of App and arr from this App instance will be updated
<Route exact path="/newtab" component={App additionalProps={additionalProps} /> // I want the updated arr from the App instance on the main page to show up here.
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
I clearly understand that, through this approach of using react-router to open a component in a new tab, I'm essentially opening a new instance of the App component in the new tab and it makes the App component on main page and App component on "/newtab" page completely unrelated.
Please let me know if I'm unclear anywhere and if I can provide you with more info. Thank you very much.
Your understanding of React is a bit skewed - you cannot open "the same instance" of a component, as components are not rendered to the DOM. Components are converted to HTML elements, so two different pages have two different DOM elements - they can't be shared.
What you're trying to do is share state between two tabs.
React does not support this, a new tab is a new app, it is a totally separate instance.
The only way to share state between two instances of an app that are open in the same browser would be to use third party / external APIs.
For example, you could connect your app to the browser's local storage. This means that both instances of the app would share the same local storage data. Be careful with this as you must not store any sensitive data (i.e. user details, passwords, bank details, access tokens) in local storage as it is susceptible to XSS and other attacks.
There is a guide here on how to do this (the author uses Redux) but I'm sure you don't NEED to use Redux to achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With