简体   繁体   中英

How to remove the child element of a div in react using useRef hook?

I want to remove the old SVG and create a new SVG whenever the chart_data value changes.

import React, {useRef, useEffect, useState} from 'react'
import * as d3 from 'd3'
import { useSelector} from "react-redux";

const Barchart = () =>{
    const chart = useRef(null);
    const chart_data= useSelector(state => state.ChartReducer);

    useEffect(() => {
        let svg = d3.select(chart.current)
        //code to create the chart
        //
        return () => {
            //How to remove the old svg element from the ref chart.current?
            //I tried
            chart.current.removeChild() // This throws an error saying expects 1 argument got 0

        }
    },[chart_data])

    return(
       <div className="bar-chart" ref={chart}></div>
    )

}

export default Barchart

chart.current.removeChild() is not removing the children of <div className="bar-chart" ref={chart}></div>

How to remove all the child element of a div which has useRef reference?

You should indicate the child element in the removeChild() method.

chart.current.removeChild(chart.current.children[0])

Node.removeChild() requires the child node to be removed as argument. If you want to remove all the child element, you can use Element.innerHTML :

chart.current.innerHTML = "";

Node.removeChild() requires a node argument (the child node to remove) that you're missing.

There's nothing React specific about this problem.

Did you maybe mean

chart.current.removeChild(svg)

?

I used the above answer ie You should indicate the child element in the removeChild() method . But It throws an error and I handle it this way:

 if (chart.current.children[0]) { chart.current.removeChild(chart.current.children[0]); }

So it checks for the child if it is present then it will remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM