I am new to javascript and react. I have done lots of Googling with no solution. I am trying to hide a button component on one of three pages/routes where it currently displays but when I try to do it, it hides on all the pages/routes. Here is the code:
const routes = [
{
path: '/:bookId/details',
title: 'Book Details',
component: BookDetailsPage,
hideButton: true
},
{
path: '/:bookId',
title: 'Details',
component: BookPage,
exact: true,
hideButton: false
},
{
path: '/',
title: 'Book',
component: BookListPage,
hideButton: false
}
];
const Page = (): React.ReactElement => {
const isBookDetailsPage = routes[0].hideButton; //returns true
return (
<ContentMasterLayout
title="Book"
action={
<Box display="flex">
//this approach hides the button on all pages
{!isBookDetailsPage &&
<BookButton transactionId={match?.params.bookId} />}
</Box>
}
>
<LocalRouter routes={routes} />
</ContentMasterLayout>
);
};
Please any help would be appreciated. Thanks in advance
I wouldn't use the hideButton
value as it'll always be true for every other page,
I'll check the current page by looking at the pathname on the route and if the route has details then isBookDetailsPage
is true
and if not then it's false
So technically your code should look like this
import { useLocation } from 'react-router-dom';
const Page = (): React.ReactElement => {
const location = useLocation();
// will be true/false
const isBookDetailsPage = location.pathname.includes('details');
return (
<ContentMasterLayout
title="Book"
action={
<Box display="flex">
{!isBookDetailsPage &&
<BookButton transactionId={match?.params.bookId} />}
</Box>
}
>
<LocalRouter routes={routes} />
</ContentMasterLayout>
);
};
In the example above, I used the useLocation()
hook on react-router-dom V5.1, but you can also use props.location.pathname
or the plain javascript window.location.pathname