I am trying to make a modal:
This is the header.jsx file:
import React from "react";
import styles from "./header.module.css";
const Header = () => {
// Get the modal
const modal = document.getElementById("myModal");
// Get the button that opens the modal
const btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
const span = document.getElementsByClassName("close")[0];
console.log(btn)
// When the user clicks on the button, open the modal
btn.onclick = () => {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = () => {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}
return (
<div className={styles.Header}>
<div className={styles.login}>
<button type="submit" id="myBtn">Login</button>
<div className={styles.modal} id="myModal">
<div className={styles.modalContent}>
<span className={styles.close}>×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
);
};
export default Header;
My btn.onclick
function is returning a null but I have the element.
I have correct IDs and className. When I console.log
btn
it gives me null
. Why is it so?
I am a beginner in ReactJs so I tried using some hooks but got some weird error.
Any help would be greatly appreciated!