'How to show a popup modal on page load in React js functional component

How to show a popup modal on page load in React js functional component.basically when the page loads the popup or modal should be visible automatically without any click



Solution 1:[1]

Most modals will have a prop to specify whether or not the modal should be open. You can simply set this to true on initialization.

Consider an example using a Dialog from the React UI library MUI:

const SimpleDialog = (props) =>
{
  const [open, setOpen] = useState(true)

  return (
    <Dialog open = {open}>
      <DialogTitle>Title</DialogTitle>
      <DialogContent>...</DialogContent>
    </Dialog>
  )
}

The open prop of the Dialog is based on the value of the state variable, which is initialized as true. You can change this value as needed through various Dialog actions. To learn more about MUI Dialogs, see the docs.

For information on useState, see the React docs.

Solution 2:[2]

class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        modalState: true
    };

    this.handleShow = this.handleShow.bind(this);
}

handleShow() {
    this.setState({ modalState: !this.state.modalState });
}

render() {
    return (
        <div>
            <div className={"modal fade" + (this.state.modalState ? " show d-block" : " d-none")} tabIndex="-1" role="dialog">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title">My Profile</h5>
                            <button type="button" className="close" onClick={this.handleShow}>
                                <span>&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">...</div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary" onClick={this.handleShow}>Close</button>
                            <button type="button" className="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

}

ReactDOM.render(, document.getElementById('root'));

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pez
Solution 2 quytechabhinav