Ad
React Component Reference Own DOM-element In Typescript
Still being quite new to React I've run across the following issue: I'm creating a component this way:
export const CSpiderWeb = (props: iSpiderWebProps) => {
const classes = useStyles();
const [drawingObject, setDrawingObject] = useState({} as iDrawingObject);
const _InitRaphael = (target : HTMLDivElement) => {
while (target.firstChild) {
target.removeChild(target.firstChild);
}
const workDrawingObject : iDrawingObject = {
width : target.offsetWidth,
height : target.offsetHeight,
centerX : target.offsetWidth / 2,
centerY : target.offsetHeight /2
}
workDrawingObject.paper = Raphael(target, workDrawingObject.width, workDrawingObject.height);
setDrawingObject(workDrawingObject);
}
var workRef = createRef<HTMLDivElement>();
_InitRaphael(workRef.current as HTMLDivElement);
return <div ref={workRef} className={classes.paperContainer}>{drawingObject.centerX}x{drawingObject.centerY}</div>
}
What I'm trying to accomplish here is get the rendered DIV element and pass it to the _InitRaphael method, but it appears that this is called before the element is rendered. Makes sense, but HOW could this be done. I've googled and googled and sometimes I run across the componentDidMount hook, but can thhat be used here and if thats the case then how?
Ad
Answer
You can't use componentDidMount
because it could only be used in class components
, when you use function component
as in your example use hooks
https://reactjs.org/docs/hooks-effect.html
I would recommend you to use the useEffect
hook which imitates componentDidMount
.
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad