React Renders at the bottom of my component! no the top - reactjs

when i click on one of the Links in the mobile view, it renders a new component for the product details page.
However the rendered view always starts at the bottom ..
how can i change this to always display the new component from the top ??

You can try this :
componentDidMount() {
window.scrollTo(0, 0)
}

for stateless component with the help of hooks you can achieve this by doing:
useEffect(() => {
window.scrollTo(0,0);
}, [])

Related

Is it possible render something before the component will unmount?

I created a custom Modal. In the component mount I put the className "visible" with a simple opacity: 1.
Since the Modal has a transition, I also want to put a className "gone" with opacity 0 in the unmount of the component.
Is it possibile wait the transition of the close before unmount it and do something like this:
useEffect(() => {
setClassname('visible');
return () => {
setClassname('gone');
setTimeout(()=>{
OK, NOW U CAN UNMOUNT!
), 200 // time of the transition}
}
}, []);
?
I think React Transition Group can help you. https://reactcommunity.org/react-transition-group/
You should not remove class in unmount, just do this logic in parent component, using React Transition Group. You can find an example
of transition here https://reactcommunity.org/react-transition-group/transition

My React app page scroll to Top is ugly. Is there a scroll method that doesn't scroll?

I understand react is a single page app. Is there a scroll method that doesn't scroll the page and is on the top by default? Or what tricks can be used to do that?
useEffect(()=>{
window.scrollTo(0,0);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[])
More clear :
I visit a page and scroll to bottom. When I go to other page using Link, the visited page scrolled from bottom to top (animated scrolled).
I hope the visited page is on the top by default. Not animated scrolled.
The scrollTo function accepts an object with options as well. This way, you can explicitly set the behavior to instant.
Also, you should use the useLayoutEffect hook to avoid any flickering after the initial render.
Please refer to the official documentation: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
import { useLayoutEffect } from 'react';
export default Page = (props) => {
useLayoutEffect(() => {
window.scrollTo({
left: 0,
top: 0,
behavior: 'instant',
});
}, []);
return (
<div>Hello World!</div>
);
};

Scroll div to bottom when rendered React

I have a div of Messages in my chat application written in React. I want the div to be scrolled to the bottom when the user loads the page for the first time in order to see the latest messages. How can I implement this?
you can use useLayoutEffect hook to see when your div is rendered and use a refrence to your div element to scrollit to end
const Messages = () => {
const divRef = useRef();
...
useLayoutEffect(() => {
if (divRef.current)
divRef.current.scrollTop = divRef.current.scrollHeight;
}, [divRef]);
...
return (
<div ref={divRef}>
...
</div>
);
};
You just need to write useEffect hook either at the start when the component renders or when all the messages are fetched. Something like this
React.useEffect(() => {
window.scrollTo(0,document.body.scrollHeight);
}, []);
or
React.useEffect(() => {
window.scrollTo(0,document.body.scrollHeight);
}, [messages]);
Depends on how you're components are structured or how the views are managed. But this is the outline how you can trigger scrollTo when a user goes to your message screen.

React useEffect strange behaviour with custom layout component

I'm trying to use scroll position for my animations in my web portfolio. Since this portfolio use nextJS I can't rely on the window object, plus I'm using navigation wide slider so I'm not actually scrolling in the window but in a layout component called Page.
import React, { useEffect } from 'react';
import './page.css';
const Page = ({ children }) => {
useEffect(() => {
const scrollX = document.getElementsByClassName('page')
const scrollElement = scrollX[0];
console.log(scrollX.length)
console.log(scrollX)
scrollElement.addEventListener("scroll", function () {
console.log(scrollX[0].scrollTop)
});
return () => {
scrollElement.removeEventListener("scroll", () => { console.log('listener removed') })
}
}, [])
return <div className="page">{children}</div>;
};
export default Page;
Here is a production build : https://next-portfolio-kwn0390ih.vercel.app/
At loading, there is only one Page component in DOM.
The behaviour is as follow :
first listener is added at first Page mount, when navigating, listener is also added along with a new Page component in DOM.
as long as you navigate between the two pages, no new listener/page is added
if navigating to a third page, listener is then removed when the old Page is dismounted and a new listener for the third page is added when third page is mounted (etc...)
Problem is : when you navigate from first to second, everything looks fine, but if you go back to the first page you'll notice the console is logging the scrollX value of the second listener instead of the first. Each time you go on the second page it seems to add another listener to the same scrollElement even though it's not the same Page component.
How can I do this ? I'm guessing the two component are trying to access the same scrollElement somewhat :/
Thanks for your time.
Cool site. We don't have complete info, but I suspect there's an issue with trying to use document.getElementsByClassName('page')[0]. When you go to page 2, the log for scrollX gives an HTMLCollection with 2 elements. So there's an issue with which one is being targeted. I would consider using a refs instead. Like this:
import React, { useEffect, useRef } from 'react';
import './page.css';
const Page = ({ children }) => {
const pageRef = useRef(null)
const scrollListener = () => {
console.log(pageRef.current.scrollTop)
}
useEffect(() => {
pageRef.addEventListener("scroll", scrollListener );
return () => {
pageRef.removeEventListener("scroll", scrollListener )
}
}, [])
return <div ref={pageRef}>{children}</div>;
};
export default Page;
This is a lot cleaner and I think will reduce confusion between components about what dom element is being referenced for each scroll listener. As far as the third page goes, your scrollX is still logging the same HTMLElement collection, with 2 elements. According to your pattern, there should be 3. (Though there should really only be 1!) So something is not rendering properly on page 3.
If we see more code, it might uncover the error as being something else. If refs dont solve it, can you post how Page is implemented in the larger scope of things?
also, remove "junior" from the "junior developer" title - you won't regret it

React-router-dom Link open at the top of page

So I am feeling pretty dum to ask this but cannot find a straight answer to it.
Do I need to give any css parameter or directly to <Link> in order for the pages on my react app open at the top?
EDIT
So refraining, everytime I click on a <Link>element at my reactJs project, the Link opens a page at the middle of the screen, not a the top.
For example. I have this component
<li ><Link to={{pathname: "/product", state: {products}}}><i className="fa fa-search"></i></Link></li>
and when I click on in, it opens a new page/component but not at the top of the page. The user needs to scroll up in order to see the top, and i would like to open new pages directly at the top!
This can be done without installing any additional libraries. You can check the official example of react-router for scroll restoration here.
You can use library react-scroll, and detect when change pathname of location, scroll to Top like this
import { animateScroll } from 'react-scroll';
useEffect(() => {
animateScroll.scrollToTop({
duration: 0
});
}, [location.pathname]);
make scrollToTop function and use it in your link tag
const scrollToTop = () => {
window.scrollTo(0, 0)
}
when user click on any link our function will make our page scroll to top.
<li onClick={scrollToTop} ><Link to={{pathname: "/product", state: {products}}}><i className="fa fa-search"></i></Link></li>
I am using the class component for my react blog. The issue got solved by adding the following method and calling it inside componentDidMount().
scrollToTop = () => {
window.scrollTo(0, 0)
}
componentDidMount() {
this.scrollToTop()
}
You can check this code is working. Live example, Blog.
If you are using a function component, then same method you can use and call it inside UseEffect().

Resources