Skip to content
Advertisement

Copy/Paste of Reactjs-Popup Example from the site does not work with useState

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

import ReactDOM from 'react-dom/client';
import './index.css';
import ControlledPopup from './ControlledPopup';

const test=ReactDOM.createRoot(document.getElementById('popup'));
test.render(ControlledPopup);

ControlledPopup.jsx

import React, { useState } from 'react';
import Popup from 'reactjs-popup';

const ControlledPopup = () => {
  const [open, setOpen] = useState(false);
  const closeModal = () => setOpen(false);
  return (
    <div>
      <button type="button" className="button" onClick={() => setOpen(o => !o)}>
        Controlled Popup
      </button>
      <Popup open={open} closeOnDocumentClick onClose={closeModal}>
        <div className="modal">
          <a className="close" onClick={closeModal}>
            &times;
          </a>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae magni
          omnis delectus nemo, maxime molestiae dolorem numquam mollitia, voluptate
          ea, accusamus excepturi deleniti ratione sapiente! Laudantium, aperiam
          doloribus. Odit, aut.
        </div>
      </Popup>
    </div>
  );
};

export default ControlledPopup;

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

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

App.js (here I use your provided component)

import ControlledPopup from "./ControlledPopup";

export default function App() {
  return (
    <div>
      <h1>Popup Test</h1>
      <ControlledPopup />
    </div>
  );
}

Check out this playground for the whole implementation.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement