Mohammad Saad
Mohammad Saad

Reputation: 127

Unable to use bootstrap-react modal in stateless function

What I want to do is add bootstrap-react modal and fire it from a stateless function. All the examples I can find requires changing the "show" in the state of component, but since Im not using af component I don't really have an idea how to do it.

https://react-bootstrap.github.io/components/modal/

Upvotes: 1

Views: 1842

Answers (3)

r g
r g

Reputation: 3901

https://react-bootstrap.github.io/components/modal/

You need state somewhere to show the modal. You can use hooks to do it in functional (not really "stateless") component using useState.

function App() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button variant="primary" onClick={() => setOpen(true)}>
        Launch demo modal
      </Button>

      <Modal show={open} onHide={() => setOpen(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setOpen(false)}>
            Close
          </Button>
          <Button variant="primary" onClick={() => setOpen(false)}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

codesandbox: https://codesandbox.io/embed/z2ky5l128l

If you don't want to do it then you need to pass prop from component that is higher in tree, like:

class App extends React.Component {
  state = {
    open: true,
  }
  render() {
    return <ModalComponent open={open} hide={() => this.setState({open: false})} />
  }
}

function ModalComponent = ({open, hide}) => (
  <Modal show={open} onHide={hide}>
    <Modal.Header closeButton>
      <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
    <Modal.Footer>
      <Button variant="secondary" onClick={hide}>
        Close
      </Button>
    </Modal.Footer>
  </Modal>
)

Upvotes: 2

Nabil CHOUKRI
Nabil CHOUKRI

Reputation: 79

I guess you can do that with useState https://reactjs.org/docs/hooks-state.html

Upvotes: 0

sathish kumar
sathish kumar

Reputation: 1507

just pass visible state from parrent like below

 class parent extends Component {

   state = {
     modalVisibility : false
   }

   handleModalVisibility = (action)=> this.setState({modalVisibility : action})

   return (
       <div>
        <button onClick={this.handleModalVisibility.bind(this,true)} >Show Modal</button>
       //use this props to show or cancel the modal
       <ModalComponent visibility ={this.state.modalVisibility} handleModal={this.handleModalVisibility} />
       </div>
   )

 }


Upvotes: 0

Related Questions