I am experienced in working with Javascript, but am pretty new to working with React. When coding purely in javascript that would be rendered in browser, I would often use:
width = document.getElementById('element_id').clientWidth
to dynamically size my svg elements to different container sizes. Does something like this exist in React? I have been trying to use the same technique, but as expected, it does not work because the the template is rendered after the script is run.
Use can use this it work. useEffect(didUpdate);. Accepts a function that contains imperative, possibly effectful code.
const App = () => {
useEffect(() => {
const width = document.getElementById('width').clientWidth;
console.log({ width });
}, []);
return(
<div id="width" />
);
}
Of course. It is very easy thing to do using "createRef" hook. Basically, document.getElementById search for a DOM element and with createRef you are assigning a reference to (virtual)DOM element and you can do every manipulation on it.
Check how it's done here:
import React, { createRef } from 'react';
export const FooComponent = () => {
const fooRef = createRef<HTMLDivElement>();
const handleClick = () => {
const divClientWidth = fooRef.current?.clientWidth;
window.alert(divClientWidth);
};
return (
<div ref={fooRef}>
<button onClick={handleClick}>Show client width</button>
</div>
);
};