Shamoon Shamoon - 2 months ago 22
React JSX Question

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

Currently, I have a

nav


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


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


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

Answer

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>
  </Nav>
);

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
  super();
  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() {
    super();
    this.state = {
      showModal: false
    }
  }

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

  render() {
    return (
      <div>
        <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>
        </Nav>
        <MyModal show={this.state.showModal} />
      </div>
    )
  }
}

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

Hope that can help

Comments