简体   繁体   中英

How can I focus a button on click in ReactJS

I have the following problem, in my web site build with nextJS and ReactJS with typescript I have products that are loaded when a button is clicked, when I click the button the items appeared and the button is scrolled down, which is the asked behavior, but when I scroll to the bottom of the page and I try to click the button the scroll remains on the same position and the items are loaded but cannot be seen, my logic is to use onFocus on the current button and when I click it to change the scroll to him, that will solve the problem when the user has scrolled down to the bottom of the page, that way it will not remain on the bottom but rather it will automatically scroll up to the button and will see the new items loaded.

The problem is that the logic to load the products are in a different component in which I am reusing the current button and right prop I am sending function to the onClick on the button. My question is how can I use onFocus. Does it has to be in the child component inside the function or in the button component. I tried to make it work on the Button component, but it doesn't work. So I am stuck for the last 4 hours and I really need a push. I would be glad if you could shine some enlargement

Here I will enter the function in the parent component for the onClick prop:

const handleLoadMoreProducts = () => {
    if (!isSearchPage) {
      const mappedBreadcrumbs: string[] = categoryData.breadcrumbs.map(
        (crumb: BreadCrumItem) => crumb.name
      );
      gtmBreadcrumbTrack(mappedBreadcrumbs);
    }

 <LoadMoreProducts handleLoadMoreProducts={handleLoadMoreProducts} />

And here is the component that uses the Button:

interface LoadMoreProductsProps {
  handleLoadMoreProducts?: (MouseEvent: React.MouseEvent<HTMLButtonElement>) => void;
  Focus?: (MouseEvent: React.MouseEvent<HTMLButtonElement>) => void;
}

const LoadMoreProducts: FC<LoadMoreProductsProps> = ({ handleLoadMoreProducts }) => (
  <div className="LoadMoreProducts">
    <Button type="button" importance="ghost" onClick={handleLoadMoreProducts}>
      Load more products
    </Button>
  </div>
);

I think what you want to do is to forward the ref of the element you are trying to focus in the Button component using React.forwardRef and combine it with the useImperativeHandle hook in order to gain the ability to trigger the focus with the ref outside of the Button component.

You could create a ref for the element you are trying to focus and call the focus() function for the ref on click.

More information regarding forwarding refs and the useImperativeHandle hook.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM