Want to open a component in new window on a click in react? You can use ReactDOM.createPortal to render a component in a new window as David Gilbertson explains in his post:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class MyWindowPortal extends React.PureComponent { constructor(props) { super(props); // STEP 1: create a container <div> this.containerEl = document.createElement('div'); this.externalWindow = null; } render() { // STEP 2: append props.children to the container <div> that isn't mounted anywhere yet return ReactDOM.createPortal(this.props.children, this.containerEl); } componentDidMount() { // STEP 3: open a new browser window and store a reference to it this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200'); // STEP 4: append the container <div> (that has props.children appended to it) to the body of the new window this.externalWindow.document.body.appendChild(this.containerEl); } componentWillUnmount() { // STEP 5: This will fire when this.state.showWindowPortal in the // parent component becomes false So we tidy up by closing the window this.externalWindow.close(); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.