Search code examples
reactjsonclickarrow-functions

Using two arrow function in onClick eventlisterner


Here is the code,

import React, { useEffect, useState } from 'react'
import './Body.css'
export default function Navbar() {
    const [value, setvalue] = useState(0);
    const [value1, setvalue1] = useState(0);
    return (
        <>
            <div>
                <h1>Our App</h1>

                <div className="back">
                    <h3>Counter</h3>
                    <button onClick={() => [() =>{setvalue(value - 1)} , ()=>{setvalue1(value1 - 1)}] }> - </button>
                    <button>{value}</button>
                    <button>{value1}</button>
                    <button onClick={()=> [() =>{setvalue(value + 1)} , ()=>{setvalue1(value1 + 1)}] } > + </button>
                </div>
            </div >
        </>
    )
}

I checked here how to pass two functions in the onClick event and this is the only way I am not getting a syntax error.

Can anyone suggest some edits to this?


Solution

  • Your click handler does not call the two functions instead, it returns two functions in an array.

    You just need to call the two functions like this:

    function Navbar() {
      const [value, setvalue] = React.useState(0);
      const [value1, setvalue1] = React.useState(0);
      return (
          <div>
            <h1>Our App</h1>
    
            <div className="back">
              <h3>Counter</h3>
              <button
                onClick={() => {
                  setvalue((value) => value - 1);
                  setvalue1((value1) => value1 - 1);
                }}
              >
                {" "}
                -{" "}
              </button>
              <button>{value}</button>
              <button>{value1}</button>
              <button
                onClick={() => {
                  setvalue((value) => value + 1);
                  setvalue1((value1) => value1 + 1);
                }}
              >
                {" "}
                +{" "}
              </button>
            </div>
          </div>
      );
    }
    
    ReactDOM.render(<Navbar />, document.querySelector('.react'));
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div class='react'></div>