I have the following useRef
which contains 4 children.
I am trying to remove a child from here based on an if check.
But getting the error:
typeError: myRef.current.removeChild is not a function.
But looking at the answers here this seems to be correct. What am I doing wrong?
How to remove the child element of a div in react using useRef hook?
//This is coming from another file. Just for reference.
const myRef = React.useRef();
export const postData = (
myRef,
token,
id1,
id2,
) => {
myRef.current.children[0].value = token;
myRef.current.children[1].value = id1;
myRef.current.children[2].value = id2;
[...myRef.current.children].forEach((child) => {
if (!child.value) {
// error on this line
myRef.current.removeChild(child);
}
});
};
you can use useEffect
hook in here, maybe this will solve your issue.
...
const myRef = useRef(null)
useEffect(() => {
myRef.current.children[0].value = token;
myRef.current.children[1].value = id1;
myRef.current.children[2].value = id2;
[...myRef.current.children].forEach((child) => {
if (!child.value) {
myRef.current.removeChild(child);
}
});
}, [myRef.current, child.value])
return (
<div ref={myRef}>
...
</div>
)
...
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.