0

I have a code that is only rendered after some data is fetched from server and variables are set. When using svg.js, it uses SVG.AddTo("#someID"), but the div containing the ID has not been rendered yet because of the conditional rendering. How do I delay the SVG.AddTo, to after the div has been rendered and the id exist? Here is the code (Some things have been removed, for example server fetching):

import React, { useEffect, useState, useRef } from "react";

import {
    CCol,
    CRow,
} from "@coreui/react";

import * as SVG from '@svgdotjs/svg.js'






const website = () => {

    var draw = SVG().addTo('#svgHere').size('100%', '100%')
    var rect = draw.rect(100, 100).attr({ fill: '#f06' })

    return (
      (typeof dataFromServer !== "undefined") &&

        <CCol>
            <CRow>
                <div id="svgHere">

                </div>
            </CRow>
        </CCol>

    );



};
export default website;

I also tried, as by the documentation of svg.js adding this:

SVG.on(document, 'DOMContentLoaded', function () {
    var draw = SVG().addTo('#test').size('100%', '100%')
    var rect = draw.rect(100, 100).attr({ fill: '#f06' })
})

But then the SVG is never rendered. I later want to create a new svg every time the value of a state changes. How can I remove the current draw? I know about useEffects dependencies but I do not know how I can remove the current SVG and replace it with another one?

Thank you for your help!

1 Answer 1

0

Make an component and put your logic there and then in Website component return

 return (
  (typeof dataFromServer !== "undefined") &&

    <CCol>
        <CRow>
            <Svg/>
        </CRow>
    </CCol>

);

Later when you want a different svg based on your state changes pass whatever you need as props to

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.