zer0day
zer0day

Reputation: 246

how do I call both of these functions with onClick on the same button?

Probably a dumb question but I'm using a a plugin for smooth scrolling to an element and I have a button on a sidebar that I want to use this plugin with but also I want the sidebar to close when I click the button. I have a function that closes the sidebar which I passed through props but I'm not really sure how to combine the two into working with one button. Basically, how can I make these two buttons into one..

import React from "react"
import "./sidebar.css"
import scrollTo from "gatsby-plugin-smoothscroll"

const Sidebar = props => {

 return (
<nav className={sidebar}>
  <ul>
    <li>
      <button onClick={props.hide}>Home</button>
    </li>
    <li>
      <button onClick={() => scrollTo("#home-page")}></button>
    </li>
  </ul>
</nav>

)
}

Upvotes: 0

Views: 53

Answers (4)

Nafeo Alam
Nafeo Alam

Reputation: 4692

Try This code:

import React from "react"
import "./sidebar.css"
import scrollTo from "gatsby-plugin-smoothscroll"

const Sidebar = props => {
  const handleClick = e => {
    scrollTo("#home-page");
    props.hide(e.target);
  };

  return (
    <nav className={sidebar}>
      <ul>
        <li>
          <button onClick={handleClick}>Home</button>
        </li>
      </ul>
    </nav>
  );
};

Upvotes: 0

Swatantra Kumar
Swatantra Kumar

Reputation: 1330

You only need to define the event separately invoke it onClick of the button.

import React from "react"
import "./sidebar.css"
import scrollTo from "gatsby-plugin-smoothscroll"
.
.
.

const Sidebar = props => {
  const ClickTheHandle = event => {
    props.hide(event);
    scrollTo("#home-page");
  };

  return (
    <nav className={sidebar}>
      <ul>
        <li>
          <button onClick={ClickTheHandle}>Home Page</button>
        </li>
      </ul>
    </nav>
  );
};

Upvotes: 0

Hamid Sarani
Hamid Sarani

Reputation: 795

you simply can call both functions like this:

<button 
  onClick={(event) => {
    scrollTo("#home-page");
    props.hide(event)
  }}
>
  Home Page
</button>

Upvotes: 0

Taghi Khavari
Taghi Khavari

Reputation: 6582

you just need to do this:

const Sidebar = props => {
  const handleClick = e => {
    props.hide(e);
    scrollTo("#home-page");
  };

  return (
    <nav className={sidebar}>
      <ul>
        <li>
          <button onClick={handleClick}>Home</button>
        </li>
      </ul>
    </nav>
  );
};

Upvotes: 1

Related Questions