Home > Software design >  How to pass a function to a component using arrow function?
How to pass a function to a component using arrow function?

Time:11-16

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.

CodePudding user response:

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

Try to replace

const CustomSwitcher = (isLeftButton, toggleSwitcher) => {

with

const CustomSwitcher = ({isLeftButton, toggleSwitcher}) => {

CodePudding user response:

const CustomSwitcher = (isLeftButton, toggleSwitcher) => { ... }

is not the correct way to build a component.

Either use the props object

const CustomSwitcher = (props) => {
    // props.toggleSwitcher
}

Or destructure props

cost CustomSwitcher = ({isLeftButton, toggleSwitcher}) => { ... }

CodePudding user response:

You need to use useState inside a functional component. In your case, inside home. Hooks cannot be used at the global level. Consequently, you need to define toggleSwitcher inside home also.

  • Related