I want to open a popup when I click a button on react, I have this but the popUp wont appear:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target={`#${props.idMessage}`}>
{props.idMessage}
</button>
<div class="modal fade" id={props.idMessage} tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
Using the react debug tools I can see that the props.id obviously differ from each one and the value on my data-target is the same of my id, as you can see the popUp should appear:

Here is modern way to achieve this using React Hooks
import React, { useState } from "react";
const PopUp = ({ idMessage }) => {
// create state `open` with default as false
const [open, setOpen] = useState(false);
return (
<>
{/* click of button toggles `open` value therefore visibility */}
<button
onClick={() => setOpen(!open)}
type="button"
className="btn btn-primary"
data-toggle="modal"
data-target={`#${idMessage}`}
>
{idMessage}
</button>
{/* If open is true show your <div /> */}
{open && (
<div
className="modal fade"
id={idMessage}
tabIndex="-1"
role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
content
</div>
)}
</>
);
};
export default PopUp;
You could consider creating the popup as a re-usable component, that just renders the props.message.
Suppose you have the button in App.js, here is how you can add the click listener on it.
class App extends Component {
state = {showPopup: false};
openPopupHandler = () => {
this.setState({showPopup: true});
}
closePopupHandler = () => {
this.setState({showPopup: false});
}
render() {
let popup = null;
if(this.state.showPopup) {
popup = (<Popup message='the text you need to display' closeMe={this.closePopupHandler}/>);
}
return(
<div>
<button onClick={this.clicked}>Click me </button>
{popup}
</div>
);
}
}
And you can define the popup component as given below.
Popup.js
const popup = (props) => {
return (
<div>
<p>{props.message}</p>
<button onClick={props.closeMe}>Close Popup</button>
</div>
);
}
Also, style the popup component with the size as per your requirement and with an z-index greater than that of the parent component.
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