Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
How to trigger function in react from foreignObject rendered with d3?

In React application I drag components

const Draggable = ({ children, onDragStart, onDragEnd }) => (
  <div
    className="draggable"
    draggable={true}
    onDragStart={onDragStart}
    onDragEnd={onDragEnd}
  >
    {children}
  </div>
);

when they dropped this components become svg elements rendered with d3js.

const onDrop = (e) => {
    e.stopPropagation();
    const newElement = {
      id: elements.length + 1,
      x: e.nativeEvent.offsetX,
      y: e.nativeEvent.offsetY,
      data: draggedData
    };
    setElements((elements) => [...elements, newElement]);
  };


 ...
    useEffect(() => {
        const svg = d3
          .select(svgRef.current)
          .attr("width", width)
          .attr("height", height);
    
        if (elements.length) {
          svg
            .selectAll(".node")
            .data(elements, (d) => d.id)
            .join(
              (enter) => {
                if (enter && prevCount !== elements.length) {
                  const { type } = enter.datum().data;
                  if (type === "person") {
                    renderNode(enter, svg, setElements, "enter");
                  } else {
                    renderInput(enter, svg, setElements, "enter");
                  }
...

One svg element contains foreignObject with input and one button (it would be more buttons).

node
      .append("foreignObject")
      .attr("width", labelWidth - labelPadding * 2)
      .attr("height", 22)
      .attr("x", labelPadding)
      .attr("y", labelPadding)
      .html((d) => {
        return `<div>
            <form>
              <input type='text' class='' />
              <button type='button' onclick='alert("The form was submitted")'>Ok</button>
            </form>
            <div class='circle'></div>
          </div>`;
      });

I want to trigger changes in state of react component when click on button inside svg. How can I handle this?

Here is working example

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!