Reputation: 241
I'm using React 18 and nextjs and I made a kind of render function like this
export const showAlert = (props: AlertProps) => {
// it will catch <div id="alert"></div> inside _document.tsx
const container = document.getElementById('alert')
if (container) {
const root = createRoot(container)
root.render(<Alert {...props} />)
}
}
And I want to use this function like this
const handleClick = () => {
if (error) {
showAlert({
type: "error",
text: "Error !"
})
}
}
But React warn of this behavior:
Anyone knows why React warn using of createRoot
for the render function ?
Upvotes: 0
Views: 461
Reputation: 203373
You should only call createRoot
on a specific container once during runtime. Update the logic to create and cache an alert root
.
Example:
let root: Root | null = null;
const showAlert = (props: AlertProps) => {
const container = document.getElementById("alert");
if (container) {
root = root ?? createRoot(container);
root.render(<Alert {...props} />);
}
};
Upvotes: 0