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.
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.
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(); } }
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