Reputation: 9863
few days ago I've started learning about reactjs + material-ui library and I'm trying to figure out
how to hide icons from the BottomNavigation
, ie:
I've created a mcve at codesandbox.io.
Also, when I click on the Login button I'd like to know which button from the BottomNavigation has been selected in order to display a message that says something like:
alert(`Page ${name_of_selected_screen} is selected`)
how would you do that?
Upvotes: 1
Views: 389
Reputation: 11166
Ciao, to hide the icon is just necessary to remove icon
props from BottomNavigationAction
. This is the easy part.
To pass screen selected from SimpleBottomNavigation
to parent App
it's a little bit more tricky. First of all you know that from BottomNavigation
onChange
function you retrieve the id of the page selected. So you could create a constant array in SimpleBottomNavigation
to map correlation between index and page name. Something like:
const pages = [
{ page: "Page1", id: 0 },
{ page: "Page2", id: 1 },
{ page: "Page3", id: 2 }
];
Ok, now we have to pass data from SimpleBottomNavigation
to App
. You could do this by add a prop on SimpleBottomNavigation
like:
<SimpleBottomNavigation pageSelected={setPageSelected} />
The function setPageSelected
looks like:
const setPageSelected = (page) => {
setPage(page);
};
Where setPage
is the set state action for page
state:
const [page, setPage] = React.useState("");
Well, now on BottomNavigation
onChange
lets call pageSelected
like:
props.pageSelected(pages.filter((el) => el.id === newValue)[0].page);
This works but there is a problem with the first page selected. At start up, if you don't click any BottomNavigationAction
, the page
in App
is not setted.
We can solve this by using useEffect
and useRef
hook on SimpleBottomNavigation
like:
const firstrender = React.useRef(true);
React.useEffect(() => {
if (firstrender.current) { // this is just a technique to run below code just one time
props.pageSelected(pages.filter((el) => el.id === value)[0].page);
firstrender.current = false;
}
});
Now it's just necessary to modify button Login onClick
:
<Button
onClick={() => {
alert("Page: " + page + " is selected");
}}
>
Login
</Button>
Done! Now alert shows page selected on SimpleBottomNavigation
.
Here your codesandbox modified.
Upvotes: 2
Reputation: 83557
How to hide BottomNavigation icons?
The easiest way to hide UI elements it to not render them. Or another way to ask your quesiton is: how do I sometimes show a button and sometimes not?
To do this in React, we use conditional rendering that looks something like this:
{ showRestore ? <BottomNavigationAction label="Page1" icon={<RestoreIcon />} /> : ''}
Now you need a way to set showRestore
. This can either be a prop that is passed in to your component or component state or global state. The exact solution to use here depends on where you determine whether or not to show the button.
Upvotes: 1