Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a component in new window on a click in react

Tags:

I have a component which displays a data. I have to open this component in a new window on clicking a button/ link from a parent component.

export default class Parent extends Component {     construtor(props) {         super(props);     }      viewData = () => {         window.open('childcomponent.js','Data','height=250,width=250');     }      render() {         return (             <div> <a onclick={this.viewData}>View Data</a></div>         )     } } 

I dont know how to invoke another component and also display it in a new size specified window.

Actually I need to send a props to that child component with which it will fetch me the data from database and render it.

like image 799
Vandhana Avatar asked Nov 30 '17 13:11

Vandhana


People also ask

How do I open a new window in Click React?

To open a page in a new tab on button click in React: When the button is clicked, use the window. open() method to load the resource.


1 Answers

You can use ReactDOM.createPortal to render a component in a new window as David Gilbertson explains in his post:

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();   } } 
like image 158
CD.. Avatar answered Oct 25 '22 10:10

CD..