Skip to content
Advertisement

How to pass a function to a component using arrow function?

FYI: I am using ES6 on ReactJS

I have a switcher. I need it to switch to the other side when clicked. If click on the side that is currently active does nothing.

Here is my sample code

import { useState } from 'react'
const {isLeftButton, setIsLeftButton} = useState(true);
const toggleSwitcher = () => {
    setIsLeftButton(!isLeftButton)
}

const home = () => {
...
    return (
        <CustomSwitcher isLeftButton={isLeftButton} toggleSwitcher={toggleSwitcher} />
    )
...
}
export default Home

Here is the code inside the CustomSwitcher

const CustomSwitcher = (isLeftButton, toggleSwitcher) => {

    const leftButton = () => {
        if (isLeftButton !== true) {
            toggleSwitcher()
        }
    }

    const rightButton = (isLeftButton, toggleSwitcher) => {
        if (isRightButton === true) {
            toggleSwitcher()
        }
    }

    return (
         <div>
             <CustomButton onClick={LeftButton}>Left Button</CustomButton>
             <CustomButton onClick={rightButton }>Right Button</CustomButton>
         </div>
        )
    }
export default CustomSwitcher

However I got this error

TypeError: toggleSwitcheris not a function
  12 |    const CustomSwitcher = () => {
  13 |        
  14 |        if (leftButton !== true) {
> 15 |            toggleSwitcher()
     | ^  16 |        }
  17 |    }
  18 | 

As I understand, when passing a function down to a component. The function is no longer a function.

And I don’t think my code is good. If you can think of a better way to do so. Please contribute.

Advertisement

Answer

You are not using the correct way to access the props.

Try to replace

const CustomSwitcher = (isLeftButton, toggleSwitcher) => {

with

const CustomSwitcher = ({isLeftButton, toggleSwitcher}) => {
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement