0
votes

I can create svg and all its component children (like rect etc.) using js in react application. However i can't give ref attribute to an element. If i see the generated source code, its ref=[object Object], thus it's not working. The code is called in componentDidMount, after appendChild. So it should work, because it's rendered in DOM already (isn't it?). ref works perfectly fine with svg elements (if not dynamically created). Can someone direct me in the right direction?

Even using the createElement function of React works: React.createElement('rect', {key: "myKey", width: 100, height: 100, ref: myRef}) But it does not create a real DOM node, which can be used with appendChild function (the error message says that). So i can't really use that either. clipPathRef.current returns the containing clipPath element, which works of course. The rect element is created and rendered, it just does not have the ref attibute correctly.

const myRef = React.createRef(); 
    const newElement = document.createElementNS("http://www.w3.org/2000/svg", 'rect');
        newElement.setAttribute("width", 100);
        newElement.setAttribute("height", 100);
        clipPathRef.current.appendChild(newElement);

        newElement.setAttribute("ref", myRef);

        console.log(myRef);//outputs [current null]
1
Ref is a special JSX attribute, it has no special properties when placed on a DOM nodeFerrybig

1 Answers

0
votes

This (newElement.setAttribute("ref", myRef)) does not work because React is never assigning the ref prop as a html attribute. React filters it out of the props and manages it on its own when a component mounts, updates or unmounts.

Looking at your code example you don´t need to use ref if you always create the <rect> element. The variable where you put your newly created element into (e.g. newElement) is basically the same as a ref, but not scoped into a current attribute.