Following the below approach to show Bootstrap 5 Toast dynamically on click of a button in React.js
import statement:
import * as bootstrap from 'bootstrap';
Button click submit handler:
let toastEl = document.getElementById('myToast');
let toast = new bootstrap.Toast(toastEl, {autohide: false});
toast.show();
render:
<div class="toast align-items-center" id="myToast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
Hello, world! This is a toast message.
</div>
<button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
</div>
<button type="button" className="btn btn-primary" id="showToast" onClick={this.showToast}>Show Toast</button>
Is there any alternate method to do this in React way, as it is NOT recommended to use document.getElementById in React? Tried by using Ref, but Toast doesn't display.
You can use the useRef
and useEffect
React hooks...
const { useState, useEffect, useRef } = React
const { Toast } = bootstrap
function ToastDemo() {
var [toast, setToast] = useState(false);
const toastRef = useRef();
useEffect(() => {
var myToast = toastRef.current
var bsToast = bootstrap.Toast.getInstance(myToast)
if (!bsToast) {
// initialize Toast
bsToast = new Toast(myToast, {autohide: false})
// hide after init
bsToast.hide()
setToast(false)
}
else {
// toggle
toast ? bsToast.show() : bsToast.hide()
}
})
return (
<div className="py-2">
<button className="btn btn-success" onClick={() => setToast(toast => !toast)}>
Toast {toast?'hide':'show'}
</button>
<div className="toast position-absolute m-4" role="alert" ref={toastRef}>
<div className="toast-body">
Hello, world! This is a toast message.
</div>
</div>
</div>
)
}