0

I am having trouble using a Bootstrap modal in ReactJS. My code renders the console.log function just fine, but it will not show the modal. Here is my code:

import React from "react"; import ReactDOM from "react-dom"; class ExternalLink extends React.Component { renderModal() { console.log("the link " + this.props.url + " was clicked.") return ( <div className="modal show"> <div className="modal-dialog modal-dialog-centered" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> ... </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data- dismiss="modal">Close</button> <button type="button" className="btn btn-primary">Save changes</button> </div> </div> </div> </div>, document.getElementById("root") ); } render() { return ( <div> <a onClick={() => this.renderModal()}>{this.props.url}</a> </div> ); } } export default ExternalLink; 

Since the Javascript seems to work, I'm thinking I did something wrong in the Bootstrap area of things. Thanks in advance!

1 Answer 1

4

That's not how react works. You can't render something from an event handler. What you do is set up some state to control what gets rendered. In your example:

class ExternalLink extends React.Component { constructor(props) { super(props) this.state = { showModal: false } } renderModal() { console.log("the link " + this.props.url + " was clicked.") return ( <div className="modal show"> <div className="modal-dialog modal-dialog-centered" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> ... </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data- dismiss="modal">Close</button> <button type="button" className="btn btn-primary">Save changes</button> </div> </div> </div> </div> ); } render() { return ( <div> <a onClick={() => this.setState({showModal: true})}>{this.props.url}</a> {this.state.showModal && this.renderModal()} </div> ); } } 

Your renderModal method should just be a separate component. Note that you'll have to put some way to set showModal to false in your modal to hide it again.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.