In my pervious blog, I explained how modal can be used in functional components. My obsession with modal continues so now, I'll go over one of the ways you can use modal in Class Components!
First start off with basic react class component:
import React, { Component } from 'react'
class ModalInClassComponents extends Component {
render() {
return (
<div>
</div>
)
}
}
export default ModalInClassComponents;
Now, in your terminal, you want to install: npm install react-responsive-modal
and import modal and style.css in your component:
import { Modal } from 'react-responsive-modal';
import 'react-responsive-modal/styles.css';
Create a state for the modal to stay closed initially:
state ={
openModal : false
}
Create a button with onClick attribute. We will call function when the button is clicked which sets the openModal
state to true
.
<button onClick={this.onClickButton}>Click Me</button>
onClickButton = e =>{
e.preventDefault()
this.setState({openModal : true})
}
Now, we need to use the Modal component and add two attributes: open
and onClose
.
open
is set to this.state.openModal
, so the modal opens when the state is true
.
onClose
works the same way as onClick
, however, in this case, we want to set the state back to false
.
<Modal open={this.state.openModal} onClose={this.onCloseModal}>
//Here you can add anything you want to reveal when the button is clicked!
<h1>You Did it!</h1>
</Modal>
onCloseModal = ()=>{
this.setState({openModal : false})
}
And that's it! You should be able to view your modal now:
I love modal because it adds a bit of oomph to your app and it's very simple and easy to use.
The full code looks like this:
import React, { Component } from 'react'
import { Modal } from 'react-responsive-modal';
import 'react-responsive-modal/styles.css';
class ModalInClassComponents extends Component {
state={
openModal : false
}
onClickButton = e =>{
e.preventDefault()
this.setState({openModal : true})
}
onCloseModal = ()=>{
this.setState({openModal : false})
}
render() {
return (
<div>
<button onClick={this.onClickButton}>Click Me</button>
<Modal open={this.state.openModal} onClose={this.onCloseModal}>
<h1>You Did it!</h1>
</Modal>
</div>
)
}
}
export default ModalInClassComponents;
Thank you for making it till the end!
Top comments (1)
thanks a lot