am trying to back whenever i click the button but its not working, please can somebody help me out on what am doing wrongly
here is the code for the home page
import Header from './Header';
import TinderCards from './TinderCard';
import SwipeIcon from './SwipeIcon';
import { useNavigate } from 'react-router-dom';
const Home = () => {
const navigator = useNavigate();
return (
<div>
<Header backButton={() => navigator.goBack()} />
<TinderCards/>
<SwipeIcon/>
</div>
)
}
export default Home;
here is the header component
<div className='header'>
{backButton ? (
<IconButton >
<PersonIcon className='header__icon' fontSize='large'/>
</IconButton>
): (
<IconButton onClick={backButton}>
<ArrowBack className='header__icon' fontSize='large'/>
</IconButton>
)}
</div>
here is the chats component
import Header from './Header'
const Chats = () => {
return (
<div>
<Header/>
</div>
)
}
export default Chats
Try:
{!backButton ? (
<IconButton>
<PersonIcon className='header__icon' fontSize='large'/>
</IconButton>
): (
<IconButton onClick={backButton}>
<ArrowBack className='header__icon' fontSize='large'/>
</IconButton>
)}
The navigate function has two signatures:
Either pass a To value (same type as <Link to>) with an optional second { replace, state } arg or
Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.
More info: https://reactrouter.com/docs/en/v6/api#usenavigate
EDIT: Also, on Header component you need to invert your logic as you are adding the onClick only when there's no backButton prop, so if should be something like:
<div className='header'>
<IconButton onClick={backButton ? backButton : null }>
<ArrowBack className='header__icon' fontSize='large'/>
</IconButton>
</div>
i remove the backButton in the home component and call the navigate function in the header component
import { IconButton } from '@mui/material';
import { ArrowBack } from '@mui/icons-material'
const Header = ({backButton}) => {
const navigate = useNavigate()
return (
<div className='header'>
{backButton ? (
<IconButton >
<PersonIcon className='header__icon' fontSize='large'/>
</IconButton>
): (
<IconButton onClick={() => navigate(-1)}>
<ArrowBack className='header__icon' fontSize='large'/>
</IconButton>
)}
)
}
export default Header