How to scroll 'onClick' component that is hidden before onClick event

Viewed 47

When I click on the image I want that it is automatically scrolled to the component which is then displayed. I tried with anchor tags, but it's not working (I believe due to the fact that the component is hidden and at the same time when it is shown it should be scrolled to it ) , useRef - I get the error 'not defined' (I believe same reason as above). Component is displyed onClick, but it does't scroll to the view-port of the user. Pls help, I'm out of the ideas :/

const WebContent = () => {
   
   const [hidden, setHidden] = useState(false)
    return (   
             <div>
               <img onClick={() => setHidden(true)} src={first}/>
              
               <div>
                 {hidden && <MyComponent/>}
               </div>
            </div>
      )}
2 Answers

Your intuition is probably right that MyComponent is not yet mounted when you try to scroll to it. A simple way to do this would be to have MyComponent scroll itself into view when it mounts, if that's the behavior you're looking for.

const MyComponent = () => {
  const ref = React.useRef(null);

  useEffect(() => {
    if (ref.current) ref.current.scrollIntoView();
  }, [ref]);

  return (
    <div ref={ref}>
      NOW YOU SEE ME
    </div>
  );
};

export default MyComponent;

One (hacky?) idea is add the ref to the surrounding div of the hidden content:

this.scrollHere = React.useRef(null);
...

return (
  <div style={{ minHeight: 1 }} ref={this.scrollHere}>
    {hidden && <div>My Hidden Component</div>}
  </div>
)

Then you can run a function onClick, which sets hidden to true (which by the way is kinda irritating. Maybe just use "shown" as a quick improvement) and also lets the ref scrollIntoView:

const showAndScroll = () => {
  setHidden(true);
  this.scrollHere.current.scrollIntoView({
    behavior: "smooth"
  });
};

The minHeight has to be placed on the div since it is at height of 0 first and this messes with the scroll function (it scrolls below the hidden content).

See working example here.

Related