My react project uses redux, but in order to trigger a "Confirm Delete" modal inside a parent I'm using the parent state to trigger the modal.
I could link the modal to the redux store, but both these methods feel like very convoluted ways of actioning the delete.
Ideally, I'd like the modal to be set up independently of state/redux, so that I can simply trigger a runModal(body, clear, callback)
function in the button
onClick Handler before confirming the delete.
What am I missing?
// Parent Component
import React, {Component} from 'react';
import { connect } from 'react-redux';
import * as actions from './actions.js';
import MyModal from '../../modal';
class EditUser extends Component {
constructor(props) {
super(props);
this.state = {
modal: {
body:null,
callback:null,
clear: null,
}
}
}
clearModal = () => { this.setState({modal: false}) }
handleUserDelete = (id, index) => {
let body = "Permanently delete user?";
this.setState({
modal: {
body,
callback:()=> { this.props.deleteUser(id, index) },
clear: this.clearModal,
}
})
}
render() {
const { updateUser, user } = this.props;
return(
<MyModal
{...this.state.modal}
/>
<button
className="btn-sm btn-outline-secondary"
onClick={() => this.handleUserDelete(user.ID, user.index)}
>Remove</button>
</div>
)
}
}
function mapStateToProps ({ account }) {
const { user } = account;
return { user };
}
export default connect(mapStateToProps,actions)(EditUser);
-
// Child Component
import React, {Component} from 'react';
import { Modal } from 'react-bootstrap';
class MyModal extends Component {
render (){
const {
title,
body,
callback,
clear,
} = this.props;
if ( callback && body ) {
return (
<div className="w-100">
<Modal.Dialog>
{title &&
<Modal.Header>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
}
<Modal.Body>{body}</Modal.Body>
<Modal.Footer>
<button
className="btn btn-sm btn-outline-secondary"
onClick={()=> {clear()}}
>Close</button>
<button
className="btn-sm btn-danger"
onClick={()=> {
callback();
clear();
}}
>Confirm</button>
</Modal.Footer>
</Modal.Dialog>
</div>
)
}
return null;
}
}
export default MyModal