Reputation: 841
I am building a web application with react. Among them, I would like to implement moving to the added element (part) when adding one part. I tried to implement it through useRef, but the way I did it was not recognized by the ref when it was added, causing an undefined error. How can I solve this?
//Parent
const focusTarget = useRef<any>([]);
const scrollTo = (id: number) => {
console.log(focusTarget.current.length);
setTimeout(() => {
focusTarget.current[id].scrollIntoView({ behavior: "smooth" });
}, 200);
};
return (
<WriteContainer>
<PartSectionContainer onScroll={scrollDetectHandler} id="section2">
{partIdList.map((id, idx) => {
return (
<Part
ref={(el) => (focusTarget.current[id] = el)}
scrollTo={scrollTo}
partID={id}
setVisibleMore={setVisibleMore}
ListLength={partIdList.length}
PartNum={idx}
key={id}
/>
);
})}
</PartSectionContainer>
</WriteContainer>
);
}
//Child
const Part = forwardRef<any, IProps>(({ PartNum, scrollTo, ListLength, setVisibleMore, partID }, ref) => {
...
//This part is the function to add the parent component.
const addPart = useRecoilCallback(({ snapshot, set }) => () => {
const partIds = snapshot.getLoadable(sectionIdListAtom).getValue();
const lastNumber = partIds[partIds.length - 1].slice(-1);
set(sectionIdListAtom, [...partIds, PartIDFormat(Number(lastNumber) + 1)]);
scrollTo(ListLength - 1);
});
return (
<PartContainer ref={ref} id={PartIDFormat(PartNum + 1)}>
...
</PartContainer>
);
});
My current implementation is to put the length of the array in the parent and move it to the DOM of the corresponding child component, but that doesn't work. It seems to be a problem that occurs because the array is managed asynchronously through Recoil, but I'm curious what other solutions are available.
Upvotes: 0
Views: 50