mohammad chughtai
mohammad chughtai

Reputation: 1994

How can I use window.scrollby with react?

I am trying to click a button which scrolls down to a specific portion of my app. So currently I have:

class Nav extends Component {
  foo(){
    console.log('baz')
    window.scrollTo(0, 100);
  }
  render() {
    return (
        <nav>
          <a href="#" onClick={()=> this.foo()}>About</a>

        </nav>
    );
  }
}

This will console.log "baz" but won't scroll down to 100

Upvotes: 1

Views: 3022

Answers (5)

A. Ahmad
A. Ahmad

Reputation: 536

Checkout this quick example for your desired result:

import React from 'react';

function ScrollExample() {
  const handleScrollButtonClick = () => {
    // Scroll down by 100 pixels vertically
    window.scrollBy(0, 100);
  };

  return (
    <div>
      <button onClick={handleScrollButtonClick}>Scroll Down</button>
      <div style={{ height: '1000px' }}>
        {/* Content to create a scrollable area */}
      </div>
    </div>
  );
}

export default ScrollExample;

Upvotes: 0

Ansh Phirani
Ansh Phirani

Reputation: 1

We have to prevent the default action of the anchor tag using event.preventDefault() method and change href="#" to href="/" in anchor tag

class Nav extends Component {

    foo(event){
       event.preventDefault();
       console.log('baz')
       window.scrollTo(0, 100);
    }

    render() {
        return (
            <nav>
              <a href="/" onClick={(event)=> this.foo(event)}>About</a>
            </nav>
        );
    }
}

Upvotes: 0

sumanta
sumanta

Reputation: 1

import react from "react";


const Stchange = ()=>{


const dev = ()=>{

window.scrollBy(0,50);

}
    return(

        <>

        <button onClick={dev}>Scroll</button>

          <h1>There are man struc Lorem Ipsum which looks reasonable. The</h1>

        </>
    )
}

export default Stchange;

Upvotes: 0

braveaccount bra
braveaccount bra

Reputation: 1

You can do like this -

const handleRef = (param) => window.scrollTo(0, param);
<p onClick={()=> handleRef(1000)} >Drops</p>

Upvotes: 0

yangli-io
yangli-io

Reputation: 17354

Remove the

href="#"

This is causing the link to link the top of the page

Upvotes: 1

Related Questions