I have a situation when SVG loaded from the server after the page render and after that, I need to add certain events to its elements. Let's say after clicking on a rect it shows an alert.
import React, { useEffect, useState } from 'react';
import css from "./room-plan.module.css";
import { Button } from "../../components";
export default function RoomPlan({ svg }) {
useEffect(() => {
var elements = Array.from(document.querySelectorAll('svg rect'));
elements.forEach(function(el) {
el.addEventListener("click", alert("hello"));
})
}, [])
return (
<div>
<h2 className={css.labels}>Select desk</h2>
<div id={css.roomPlan} dangerouslySetInnerHTML={{__html: svg, }}></div>
<div className={css.bookingButtons}>
<Button>CANCEL</Button>
<Button>BOOK DESK</Button>
</div>
</div>
);
}
But it totally does not work. Just does not add any events on elements. Cuz when it looks for the required selector it does not exist yet.