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?
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?
Share Improve this question asked Dec 23, 2020 at 13:38 Frank DavidFrank David 3171 gold badge5 silver badges10 bronze badges4 Answers
Reset to default 9You 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 i.e. 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.