Gabi C
Gabi C

Reputation: 481

React - Scrolling to components from navigation bar

I am trying to create a webapp in React where all modules are loaded when the page is loaded.. when clicking on the nav module I would like to scroll down to the module which has chosen. I have a parent module which has the and 3 other . What am I doing wrong? I have tried to console.log case: 1 to see what is wrong but that doesn`t seem to work either.

App.js

class App extends Component {

  constructor(props){
     super(props);
     this.MyStory = React.createRef();
     this.Portfolio = React.createRef();
     ...
     this.scrollToContent = this.scrollToContent.bind(this);
   }

  scrollToContent(content) {
      switch(content) {
      case 1:
        this.MyStory.current.scrollIntoView({behavior: 'smooth'});
        break;
      case 2:
        this.Portfolio.current.scrollIntoView({behavior: 'smooth'});
    }

  }

  render() {
    return ( 

    <div className="App">
      <Nav scrollToContent={this.scrollToContent} />
      <MyStory scrollToTop={this.scrollToTop} ref={this.MyStory}/>
      <Portfolio scrollToTop={this.scrollToTop} ref={this.Portfolio}/>
      ...
    </div>

    );
  }

}

export default App;

MyStory.js

const MyStory = React.forwardRef((props, ref) => {

        return (
        <div className="story_box" ref={ref}>
        <p> ....
        </p>
        </div>

        );
});

export default MyStory;

Nav.js

...
class Nav extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "slider",
        };      
    }

    onMenuClick = (event) => {
        if (this.state.id === "slider"){
            this.setState({id: "sliderOut"});
        }
        else (this.setState({id: "slider"}));
    }





    render () {
        return (
            <nav id="navigation" className={this.props.navStatus}>
            <div className="links">
            <a onClick={this.onMenuClick}>Menu</a>
                 <div id={this.state.id}>
                        <a id="myStory" onClick={this.scrollToContent}>My Story</a>
                        <a id="portfolio">Portfolio</a>
                        <a id="contact">Contact</a>
                </div>
            </div>
            </nav>

        );
        }
}

export default Nav;

Upvotes: 1

Views: 4380

Answers (1)

Gabi C
Gabi C

Reputation: 481

So basically how I solved it: I have moved the Nav to the parent App and then I have assigned a ref= to each component. App.js

....
...

<a onClick={()=> {scrollToComponent(this.MyStory,{offset: 0, align: 'top', duration: 1000})}}>My Story</a>

...

<MyStory scrollToTop={this.scrollToTop} ref={(MyStory) => { this.MyStory = MyStory; }}/>

Everything is on one page when it loads and scrolls absolutely fine!! :)

Upvotes: 1

Related Questions