aspiringsomeone
aspiringsomeone

Reputation: 623

Linking to a different react component on the same page

I am currently using React to make a website. My plan is to have a navigation bar that has buttons to link to another component on the page, like an about section for example. How can I do that with browserrouter?

Thanks

Upvotes: 1

Views: 13074

Answers (1)

Sabbir Ahmed
Sabbir Ahmed

Reputation: 1704

This can be the simplest approach:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.main = React.createRef();
  }
  renderMain() {
    return (
      <div style={styles.component}>
        <div style={styles.home}>
          <h1>Home</h1>
        </div>
        <div style={styles.about} ref={this.main}>
          <h1>About</h1>
        </div>
      </div>
    );
  }
  handleScroll = e => {
    e.preventDefault();
    const main = this.main.current;
    window.scrollTo({
      top: main.offsetTop,
      left: 0,
      behavior: "instant"
    });
  };
  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <div>
            <div style={styles.nav}>
              <Link style={styles.link} to="/">
                Home{" "}
              </Link>
              <Link style={styles.link} onClick={this.handleScroll} to="/about">
                About{" "}
              </Link>
              <Link style={styles.link} to="/contact">
                Contact{" "}
              </Link>
            </div>

            <Switch>
              <Route exact path="/" component={() => this.renderMain()} />
              <Route exact path="/contact" render={() => <h1>Contact Us</h1>} />
              <Route render={() => <h1>Page not found</h1>} />
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

I made a small demo at CodeSandbox, to show you a live example.

Please have a look right here: https://codesandbox.io/s/ovlq4lpqp9

Hope this helps.

EDIT: you would have to assign a 'ref' to the component you like to scroll into, and the scroll event has to be handled with onClick event from the nav link, as I have shown in the above code.

I have updated my codesandbox demo (see the link above) to help you out.

Upvotes: 4

Related Questions