Home > Enterprise >  How do I call 2 functions with a onClick event in NextJS?
How do I call 2 functions with a onClick event in NextJS?

Time:04-28

I already have 2 constants that in my NextJs app => "toggleMenu" and "changeLanguage". When someone clicks on the language changer inside the menu I need it to call these two functions.

I have tried this, but it doesn´t seem to work in my code, it gets stuck on one of the functions saying it is not defined. If I try just running that function alone it does work as intended, so the problem must be this code:

onClick={() => { changeLanguage(); toggleMenu() }}

I found this online but it also does not work because of the syntax I believe:

onclick="f1();f2()"

Can anyone suggest anything else? Thanks

EDIT:

Here are the 2 functions I am trying to call but get an error on the "changelanguage" function, specifically on => undefined when reading "e.target.value".

const Navbar = (props) => {
  
  const [isOpen, setOpen] = useState(false);
  const toggleMenu = () => setOpen(!isOpen);

  useEffect(() =>{
    document.body.style.overflowY = isOpen ? 'hidden' : 'auto';
  }, [isOpen])

  const router = useRouter();
  const { locale } = router
  const t = locale === 'en' ? en : es;

  const changeLanguage = (e) => {
    router.push(router.pathname, router.pathname,{
        locale: e.target.value,
    })
  }

  return (
      <header className="relative bg-black">
        <div className="w-full px-5 sm:px-10">
          <div className="flex justify-between items-center py-1 md:space-x-10">

            {/* Logos on the left */}

            <div className="flex justify-start lg:w-0 lg:flex-1">
            </div>

            {/* Hamburger menu icon */}

            <div className="flex md:hidden">
              <button aria-label="menu" onClick={toggleMenu} className="flex text-white hover:text-gray-500">
              </button>
            </div>

            {/* nav links and language changer*/}

            <nav className="hidden md:flex space-x-10 font-light text-white">
              <Link href="servicios">
                <a className='hover:border-b' >{t.navbar.serviciosLink}</a>
              </Link>

              <select defaultValue={ router.locale } onChange={changeLanguage} className='bg-black text-white'>
                <option className=' font-light' value='es'>ES</option>
                <option className=' font-light' value='en'>EN</option>
              </select>
            </nav>
          </div>
        </div>
        {isOpen && (
          <div className="absolute top-0 flex flex-col place-content-between w-full h-screen transition transform origin-left md:hidden bg-white z-50 px-5 sm:px-10 py-1">

            <div className="flex items-center justify-between">

              {/*Left logo*/}

              <div className='flex'>
                
              </div>

              {/* close icon*/}

              <div className="flex">
                <button aria-label="close-menu" onClick={toggleMenu} className="text-black hover:text-gray-500">
                </button>
              </div>

            </div>

            {/* navigation links */}

            <div className="flex">
            </div>

            {/* social links and language changer */}

            <div className='flex text-black text-xl font-light justify-between mb-5'>
              
              <div className='flex flex-col'>
                  <button onClick={ changeLanguage } className='cursor-pointer font-light' value='es'>ES</button>
                  <button onClick={ changeLanguage } className='cursor-pointer font-light' value='en'>EN</button>
              </div>
              
            </div>

          
            
          </div>
        )}
      </header>
  );
};

export default Navbar

CodePudding user response:

You cannot use e.target.value on the onClick event of a button. What I would do is create another function, handleSelectChange that would keep the state of the selected option.

.....
const [selectValue, setSelectValue] = useState("defaultValue");
.....
const handleSelectChange = (event) => {
  setSelectValue(event.target.value);
}
.....
<select defaultValue={ router.locale } onChange={handleSelectChange} className='bg-black text-white'>

Then for your button call your changeLanguage function which is now implemented to use the state variable

  const changeLanguage = (e) => {
    router.push(router.pathname, router.pathname,{
        locale: selectValue,
    })
  }

To be honest we don't really understand where the actual problem is. Is it the undefined event or the fact you can't call two functions.

CodePudding user response:

You can call two functions in one click event



export default function Somepage() {

  const functionOne = event =>{
    console.log("function one");
    
  }
  
  const functionTwo = event =>{
    console.log("function two");

  }

  const mainFunction = event => {
    functionOne(event)
    functionTwo(event)
  }

  return (
    <>
    <button onClick={mainFunction}>click to change</button>
    </>
  )
}

  • Related