Hey I have one question about ReactJS, because I try make modal using react-bootstrap and open it in another component. But nothing happens, please look on my code and give me some advices. I try invoke fuunction from LoginModal component using onClick="LoginModal.handleShow" but this no working.
import React, { Component } from 'react';
import {
Popover,
Tooltip,
Modal
} from 'react-bootstrap';
class LoginModal extends React.Component {
constructor(props, context){
super(props, context);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
show: false
}
}
handleShow() {
this.setState({ show: true })
}
handleClose(){
this.setState({ show: false })
}
render() {
return (
<div>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal Heading</Modal.Title>
</Modal.Header>
<Modal.Body>
<h1>This is modal body</h1>
</Modal.Body>
</Modal>
</div>
)
}
}
export default LoginModal
And App component which is rendered
import React, { Component } from 'react';
import LoginModal from './components/Login/Login'
import {
Navbar,
NavItem,
Nav,
Button
} from 'react-bootstrap';
import {
BrowserRouter as Router,
Route,
Switch,
} from 'react-router-dom'
class App extends Component {
render(){
return (
<Router>
<div className="menu-bar">
<LoginModal></LoginModal>
<Navbar inverse collapseOnSelect>
<Nav>
<NavItem>
<Button onClick={LoginModal.handleShow}>Login</Button>
</NavItem>
</Nav>
</Navbar>
<Switch>
<Route exact path="/" component={Home}/>
</Switch>
</div>
</Router>
)
}
}
export default App;
Set up the Modal ComponentInside the App component, add a button that will open up the modal. In the handleShow() function, set a Boolean state value to true and use it to display or trigger the modal. Now, add the Modal component after the button.
Use ref keyword to take reference of LoginModal. Then call handleShow from the reference.
class App extends Component {
loginModalRef = ({handleShow}) => {
this.showModal = handleShow;
}
onLoginClick = () => {
this.showModal();
}
render(){
return (
<Router>
<div className="menu-bar">
<LoginModal ref={this.loginModalRef} ></LoginModal>
<Navbar inverse collapseOnSelect>
<Nav>
<NavItem>
<Button onClick={this.onLoginClick}>Login</Button>
</NavItem>
</Nav>
</Navbar>
<Switch>
<Route exact path="/" component={Home}/>
</Switch>
</div>
</Router>
)
}
}
Here I prepare stackblitz snippet for you to test it online. https://stackblitz.com/edit/react-bxn5kj?file=index.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With