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

Viewed 9006

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?

3 Answers

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)

?

Related