I'm trying to write a modal window on React Js so that it appears immediately after the page loads. Checking like in native JS through window.onload = funciton () {} does not work.

In addition, I would like to ask about the correctness of my thinking: I create the ModalWindow component (for example) .js, write the markup there and in the render () {} I write the JS code. Then stylize and launch already in the component of the main page?

import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Modal.css'; import Link from '../Link'; class Modal extends React.Component { static propTypes = { model: PropTypes.object.isRequired, }; render() { window.onload = function () { document.getElementsByClassName('closeBtn').onClick = function () { document.getElementsByClassName('modalWindow').style.display = 'none'; }; }; return ( <div className={s.modalWindow}> <div className={s.modal}> <h1>Modal window</h1> <p>fdsifjiodsjfiodsjiofjdsiojfioejwfiowejio jioewfjfiojewifwe jiowfj</p> <button className = {s.closeBtn}></button> </div> </div> ); } } export default withStyles(s)(Modal); 
  • Give an example code! - Ihor Tkachuk
  • @IhorTkachuk edited the record - Vladyslav Tereshyn

1 answer 1

In order to show the component after the page loads, you need to use the life-cycle methods as well as the internal state of the component. To access the DOM elements of a component, you need to use refs .

The easiest option is something like that. In the constructor, we define the initial state of the window:

 constructor() { super(); this.state = { open: false, } } 

Further methods for state management:

 hide() { this.setState({ open: false, }); } show() { this.setState({ open: true, }); } 

After the component has been rendered, in the method componentDidMount() show the window:

 componentDidMount() { this.show(); } 

and fix the render() method a bit

 return ( <div className={this.state.open ? 'show': 'hide'}> <div className={s.modal}> <h1>Modal window</h1> <p>fdsifjiodsjfiodsjiofjdsiojfioejwfiowejio jioewfjfiojewifwe jiowfj</p> <button onClick={() => this.hide()} className = {s.closeBtn}></button> </div> </div> ); 
  • I thank you for the clear and complete answer, but when you press the button, the window remains and does not close ... - Vladyslav Tereshyn
  • most likely it is a matter of styles, incorrectly styled and here. Thanks again, I hope for a hint in case of some minor issues. - Vladyslav Tereshyn