Home > Mobile >  (REACT)Buttons in popup container cause whole container to dissapear
(REACT)Buttons in popup container cause whole container to dissapear

Time:04-07

I'm using from 'reactjs-popup' and when I add a button to the content being popup'd and click said button, it causes my entire popup container to dissapear. I don't want this to happen and I'm not sure how to prevent it. Relevant code:

const createCard = (src, text, price, key) => (
    <Popup
      trigger={
        <button className="popup-card">
          <div className="card">
            <img className="card-image" src={src} alt="card-img" />
            <h3 className="card-name">{text}</h3>
            <p className="card-price">{`$${price}`}</p>
          </div>
        </button>
      }
      key={key}
    >
      {popupContainer}
    </Popup>
  );

  const popupContainer = () => (
    <div className="popup-container">
      <button
        type="button"
        className="popup-input-buttons"
        onClick={subtractItem}
      >
        -
      </button>
      <input type="text" className="popup-input"></input>
      <button type="button" className="popup-input-buttons" onClick={addItem}>
         
      </button>
    </div>
  );

State:


    const [items, setItems] = useState(0);
        
    // Manipulate items state
    const addItem = () => setItems(items   1);
          
    const subtractItem = () => setItems(items - 1);

EDIT: When changing the add/subtractItem functions to:

    addItem = (e) => {
    e.target.preventDefault();
    setItem(item   1);
    }

The popup container stays open onClick, but the setItem state setter no longer works.

CodePudding user response:

try adding closeOnDocumentClick prop to your Popup, by default it is set to true, so it may cause you to close your popup if you click on any contents in the popup. Change to false should fix the problem.

<Popup
      ...
      closeOnDocumentClick={false}
    >
      {popupContainer}
</Popup>

Here is the doc: https://react-popup.elazizi.com/component-api#closeondocumentclick

closeOnDocumentClick# bool | true

Close popup when the overlay clicked

CodePudding user response:

Issue has been resolved after removing the Popup react component from my createCard() function and instead making a function purely for the Popup component.

const createCard = (src, text, price, key) => (
    <div className="card">
      <img className="card-image" src={src} alt="card-img" />
      <h3 className="card-name">{text}</h3>
      <p className="card-price">{`$${price}`}</p>
    </div>
  );

  function popupCard(card) {
    return (
      <Popup
        trigger={
          <button type="button" className="popup-card">
            {card}
          </button>
        }
      >
        <div>
          <PopupContainer addItem={addItem} subtractItem={subtractItem} />
        </div>
      </Popup>
    );
  }
  • Related