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
JavaScript
x
15
15
1
import { useState } from 'react'
2
const {isLeftButton, setIsLeftButton} = useState(true);
3
const toggleSwitcher = () => {
4
setIsLeftButton(!isLeftButton)
5
}
6
7
const home = () => {
8
9
return (
10
<CustomSwitcher isLeftButton={isLeftButton} toggleSwitcher={toggleSwitcher} />
11
)
12
13
}
14
export default Home
15
Here is the code inside the CustomSwitcher
JavaScript
1
23
23
1
const CustomSwitcher = (isLeftButton, toggleSwitcher) => {
2
3
const leftButton = () => {
4
if (isLeftButton !== true) {
5
toggleSwitcher()
6
}
7
}
8
9
const rightButton = (isLeftButton, toggleSwitcher) => {
10
if (isRightButton === true) {
11
toggleSwitcher()
12
}
13
}
14
15
return (
16
<div>
17
<CustomButton onClick={LeftButton}>Left Button</CustomButton>
18
<CustomButton onClick={rightButton }>Right Button</CustomButton>
19
</div>
20
)
21
}
22
export default CustomSwitcher
23
However I got this error
JavaScript
1
9
1
TypeError: toggleSwitcheris not a function
2
12 | const CustomSwitcher = () => {
3
13 |
4
14 | if (leftButton !== true) {
5
> 15 | toggleSwitcher()
6
| ^ 16 | }
7
17 | }
8
18 |
9
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
JavaScript
1
2
1
const CustomSwitcher = (isLeftButton, toggleSwitcher) => {
2
with
JavaScript
1
2
1
const CustomSwitcher = ({isLeftButton, toggleSwitcher}) => {
2