I’m trying out example code provided by Reactjs-Popup at https://react-popup.elazizi.com/controlled-popup/, but it doesn’t seem to work. I pretty much copy/pasted the code. What am I missing? I can make the popup to work if I remove all references to “useState”.
index.js
JavaScript
x
7
1
import ReactDOM from 'react-dom/client';
2
import './index.css';
3
import ControlledPopup from './ControlledPopup';
4
5
const test=ReactDOM.createRoot(document.getElementById('popup'));
6
test.render(ControlledPopup);
7
ControlledPopup.jsx
JavaScript
1
28
28
1
import React, { useState } from 'react';
2
import Popup from 'reactjs-popup';
3
4
const ControlledPopup = () => {
5
const [open, setOpen] = useState(false);
6
const closeModal = () => setOpen(false);
7
return (
8
<div>
9
<button type="button" className="button" onClick={() => setOpen(o => !o)}>
10
Controlled Popup
11
</button>
12
<Popup open={open} closeOnDocumentClick onClose={closeModal}>
13
<div className="modal">
14
<a className="close" onClick={closeModal}>
15
×
16
</a>
17
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae magni
18
omnis delectus nemo, maxime molestiae dolorem numquam mollitia, voluptate
19
ea, accusamus excepturi deleniti ratione sapiente! Laudantium, aperiam
20
doloribus. Odit, aut.
21
</div>
22
</Popup>
23
</div>
24
);
25
};
26
27
export default ControlledPopup;
28
Advertisement
Answer
I think your problem comes from the way you’re trying to render your component in index.js
.
Since if I try to render it the way I’m used to, the code you’ve provided worked.
I implemented it like this:
index.js
JavaScript
1
14
14
1
import { StrictMode } from "react";
2
import { createRoot } from "react-dom/client";
3
4
import App from "./App";
5
6
const rootElement = document.getElementById("root");
7
const root = createRoot(rootElement);
8
9
root.render(
10
<StrictMode>
11
<App />
12
</StrictMode>
13
);
14
App.js (here I use your provided component)
JavaScript
1
12
12
1
import ControlledPopup from "./ControlledPopup";
2
3
export default function App() {
4
return (
5
<div>
6
<h1>Popup Test</h1>
7
<ControlledPopup />
8
</div>
9
);
10
}
11
12
Check out this playground for the whole implementation.