简体   繁体   中英

Open a modal popUp in React

I have this button in react:

<button type="button" className="btn btn-primary" onClick={()=>openPopUp(object)}>
                                            Manage Permissions
</button>

and when I click the buton I want to open this popUp:

PopUp.js:

const PopUp = (props) => {
return (
    <div className="modal fade" tabIndex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">{props.object.name}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {props.object.permissions.map((permission) => {
                        return (
                            <li key={permission.code}>
                                {permission.name}
                                {props.showDeleteButton(permission.id, props.object.name)}
                                <p> </p>
                            </li>
                        )
                    })}
                    <form onSubmit={e => props.addPermission(e, props.object)}>
                        <label>
                            Insert a permission:
                         <input type="text" value={props.object.value} onChange={props.handleChange} />
                        </label>
                        <input type="submit" value="Submit" />
                    </form>
                </div>
            </div>
        </div>
    </div>
)

}

To do that, I did this, but the pop up wont open:

 let openPopUp=(object)=>{
    return   <PopUp object={object} cont={cont} onChange={handleChange} addPermission={addPermission} showDeleteButton={showDeleteButton}/>
}

There is any error thrown, the popUp just doesn´t open.

It is because openPopUp is a onclick handler, it will not return anything to render. To achieve your goal, simply use a state variable with initial value as false, and update that value in openPopUp method. Use that bool for conditional rendering of PopUp component.

Like this:

constructor() {
  super();
  this.state = {
    openPopUp: false,
    object: null
  }
}

openPopUp(object) {
  this.setState({
    openPopUp: true,
    object: object
  })
}


render() {
  return (
    <div>
      ....
      {this.state.openPopUp && 
        <PopUp object={this.state.object} cont={cont} onChange={handleChange} addPermission={addPermission} showDeleteButton={showDeleteButton} />}
      ....
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM