Semantic react ui Popup close button
Asked Answered
P

2

8

I'm using semantic-react-ui's Popup component and I was wondering how to trigger close popup event by clicking a button inside the popup without using jquery.

Thank you

Predisposition answered 15/2, 2018 at 23:25 Comment(0)
A
15

According to the docs, you have to create a controlled Popup.
Create a component which nests the Popup component, and maintain a state in it:

class ControlledPopup extends React.Component {
  constructor() {
    super();
    this.state = {
      isOpen: false
    };                  // state to control the state of popup
  }
  
  handleOpen = () => {
    this.setState({ isOpen: true });
  }
  
  handleClose = () => {
    this.setState({ isOpen: false });
  }
  
  render() {
    return (
      <div>
        <Popup
          trigger={<button>click to open</button>}
          content={<button onClick={this.handleClose}>click to close</button>}
          on='click'
          open={this.state.isOpen}
          onOpen={this.handleOpen}
        />
      </div>
    );
  }
}
Ailey answered 16/2, 2018 at 5:1 Comment(5)
I would add onClose={this.handleClose} to enable the default behavior of closing when clicking outside the menu.Jobina
Can I add multiple buttons inside content? I want to show a confirm and close buttons in popupUnstopped
What if you have multiple popups on the same page? This solution would open them all unfortunately..Nissensohn
You have to namespace the state by having separate keys in state, i.e., isPopup1Open, isPopup2Open, and so on.Ailey
Note that the doc changed. Here is the updated version: react.semantic-ui.com/modules/popup/#usage-controlledIonosphere
I
1

Here is the TS + React Hooks version of the above:

import { FC, useState } from 'react';

import { Popup } from 'semantic-ui-react';

const ControlledPopup: FC = () => {
    const [isOpen, setIsOpen] = useState(false);
    return (
        <Popup
            trigger={<button>click to open</button>}
            content={<button onClick={() => setIsOpen(!isOpen)}>click to close</button>}
            on="click"
            open={isOpen}
            onOpen={() => setIsOpen(!isOpen)}
        />
    );
};

export default ControlledPopup;
Ionosphere answered 8/1, 2021 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.