0

I am trying to access the value of current scroll position inside a Function. The two parameters are working fine and can be assessed, but when I am using the scrollPos state, it says undefined but I can see its actual value outside the function. How can I access it inside of the function. I am using react-dnd for implementing drag n drop and react-pdf for showing react pdf

  import { useDrag, useDrop } from 'react-dnd';
  import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';

  const [scrollPos, setScroll] = useState();
  const containerRef = useRef();
  const [addedFields, setAddedFields] = useState([]);

  const handleScroll = (event) => {
    const { scrollHeight, scrollTop, clientHeight } = event.target;
    const scroll = scrollHeight - scrollTop - clientHeight;
    const intScroll = parseInt(scroll, 10);
    setScroll(1470 - intScroll);
  };

  const [, drop] = useDrop(() => ({
    accept: 'card',
    drop: (item, monitor) => {
      const offset = monitor.getSourceClientOffset();
      if (offset && containerRef.current) {
        const dropTarget = containerRef.current.getBoundingClientRect();
        markField(item, {
          x: offset.x - dropTarget.left,
          y: offset.y - dropTarget.top,
        });
      }
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  }));

  console.log('Outer', scrollPos);                      // someValue

  const markField = (item, cordinates) => {
    console.log('Inner', scrollPos);                    // undefined
    const fieldDetails = {
      url: item.url,
      id: item.id + 1,
      cordinates: {
        x: 490 + cordinates.x,
        y: 665 + cordinates.y + window.scrollY,
      },
    };
    // Set fields
    setAddedFields((state) => ([...state, fieldDetails]));
  };

  const renderDoc = () => (
  <div style={{ overflowY: 'scroll' }} onScroll={handleScroll}>
  <Grid container justify="center" style={{ position: 'relative' }}>
    <Document
      file={acceptedFiles[0]}
      onLoadSuccess={onDocumentLoadSuccess}
      renderMode="canvas"
    >
      <Grid ref={drop} container style={{ height: '1080px', position: 'relative' }} justify="center">
        {[...Array(numPages).keys()]
          .map((x, i) => i + 1)
          .map((page) => (
            <Page
              key={page}
              renderAnnotationLayer
              renderInteractiveForms
              pageNumber={page}
              width={windowWidth * 0.6}
              scale={1}
            />
          ))}
        {addedFields.length > 0 && addedFields.map((field) => ([
          <DraggableField id={field.id} url={field.url} cordinates={field.cordinates} />,
        ]))}
      </Grid>
    </Document>
  </Grid>
</div>);
LauJk_78
  • 24
  • 4
  • Please include some more code. I'm assuming all that code is in one component? – code Feb 21 '22 at 20:30
  • 1
    It doesn't make sense that `scrollPos` returns a value in your outer console.log since `handleScroll` has never been called... likely you're calling `markField` on (only) the first render, while the plain `console.log` is called on all the re-renders, so after a scroll you can see the value of the outer log. Also, how do you know which log belongs to which log? Can you please label them with `console.log("Outer:", scrollPos);` and `console.log("Inner:", scrollPos);`? – code Feb 21 '22 at 20:33
  • I think the edited code would be enough, all that code is inside a functional component which for this problem i can say only renders the renderDoc function – LauJk_78 Feb 22 '22 at 09:28
  • Okay, it appears that you are using hooks *outside* a React component, which is perfectly... illegal React. Hook calls belong in function components, and **nowhere else**. That's a problem besides the one I pointed out in the other comment. – code Feb 22 '22 at 20:28

0 Answers0