I want to export function from one of my functional component that is using hooks to another one. I want to prevent redundant code appearing in my components.
I have tried to create separate function.js file where I wanted to place some of my functions but useDispatch hook makes it impossible as it throws hell a lot of errors in every attempt to make it work.
I was searching for solution and trying some export statements in different combinations.
What I want to do is to export my toggleDrawer function from Layout component to other components and here's my code. I'm sure it's very easy and I'm missing something.
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import Header from '../Header/header'
import DrawerItems from '../DrawerItems/drawerItems'
import { REDUCERS } from '../../Config/config'
import Container from '@material-ui/core/Container'
import Drawer from '@material-ui/core/Drawer'
import { makeStyles } from '@material-ui/core/styles'
const useDrawerStyles = makeStyles({
paper: {
width: '175px',
padding: '10px'
}
})
const Layout = props => {
const { isDrawerOpened } = useSelector(state => {
return {
...state.interface_reducer
}
})
const dispatch = useDispatch()
const drawerClasses = useDrawerStyles()
const toggleDrawer = (side, open) => event => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return null
}
dispatch({
type: REDUCERS.TOGGLE_DRAWER,
payload: open
})
}
return (
<Container>
<React.Fragment>
<Header/>
<Drawer classes={{paper: drawerClasses.paper}} open={isDrawerOpened} onClose={toggleDrawer('left', false)} >
<DrawerItems/>
</Drawer>
{ props.children }
</React.Fragment>
</Container>
)
}
export default Layout
dispatcheras parameter (and bind the correct arguments in a lambda, you're already doing this then it won't hurt). Define your custom hook (not something I'd do here). Just extract the common logic and share that, event handlers are seldom shared but some of their logic might be. In general: do not overthink the "no duplication" guideline, sometimes it just does not make sense. Also I'd check theonCloselogic, it is more convoluted than it should be...you're calling a function to return the handler...it might be a lambda for the handler itselfonCloseis correct, it's doesn't fire on render, i have checked, it's only a prop passed toDrawercomponent.