Shamoon Shamoon - 1 year ago 114
React JSX Question

How can I open a modal from a navbar with react-bootstrap?

Currently, I have a


<Nav pullRight className="navright">
<NavItem href="#" className={this.state.signedIn ? '' : 'hidden'}>{}</NavItem>
<NavItem eventKey={2} href="#" className={this.state.signedIn ? 'hidden' : ''}>Login</NavItem>
<NavItem eventKey={1} href="#" className={this.state.signedIn ? 'hidden' : ''}>Sign Up</NavItem>

I don't know what
is or if it's needed. But I want to open up my modal (called
) when either of those are clicked. I want to open
passing an attribute of either

How can this be done? I'm using
if that matters.

Answer Source

If you look at the code eventKey is only for the alert. So you alert the number pass ;)

function handleSelect(selectedKey) {
  alert('selected ' + selectedKey);

const navInstance = (
  <Nav bsStyle="pills" activeKey={1} onSelect={handleSelect}>
    <NavItem eventKey={1} href="/home">NavItem 1 content</NavItem>
    <NavItem eventKey={2} title="Item">NavItem 2 content</NavItem>
    <NavItem eventKey={3} disabled>NavItem 3 content</NavItem>

If you want to open modal look at the modal code.

getInitialState() { // This is the old way but can work
    return { showModal: false };

constructor() { // New way
  this.state = {
    showModal: false

  close() {
    this.setState({ showModal: false });

  open() {
    this.setState({ showModal: true });

And your modal need this code <Modal show={this.state.showModal} onHide={this.close}>

So here you just need to call the open function and the close for close it. All working by the state of react.

If you use redux you can make a reducer who see if the toggleModal is false. And with a action you can dispatch it to true.

This is a version for your own problem

class NavInstance extends React.Component {
  constructor() {
    this.state = {
      showModal: false

  handleToggleModal() {
      showModal: !this.state.showModal

  render() {
    return (
        <Nav bsStyle="pills">
          <NavItem href="/home">NavItem 1 content</NavItem>
          <NavItem title="Item">NavItem 2 content</NavItem>
          <NavItem disabled>NavItem 3 content</NavItem>
          <NavItem onClick={() => this.handleToggleModal()}>Show Modal</NavItem>
        <MyModal show={this.state.showModal} />

const MyModal = ({ show }) => 
  <Modal show>
    My Modal

Hope that can help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download