Issue
I created a hook to toggle the visibility of a NavBar in my webpage (this is done in NavBar.jsx), I need to toggle the navbar elsewhere in my code, namely under Journey.jsx, can I pass these as params? How should I approach this?
Here are the essential/boiled-down excerpts of my code if they can help....
App.jsx:
function App () {
return (
<Router hashType="hashbang">
<div className="App">
<NavBar />
<Switch>
<Route exact path="/l" component={() => <Lorem/>} />
<Route exact path="/j" component={() => <Journey/>} />
<Route exact path="/i" component={() => <Ipsum/>} />
</Switch>
</div>
</Router>
);
}
NavBar.jsx:
function NavBar () {
//I need access to these in Journey.jsx
const [sidebar, setSidebar] = useState(false);
const showSidebar = () => setSidebar(!sidebar);
return(
//elaborations about the menu where I use these functions/varariables
);
}
Journey.jsx:
function Journey () {
return (
//some unimportant divs
<button onClick={****I need access to showSidebar here****} ></button>
);
}
The way my NavBar is configured is so that the hamburger icon that toggles it is visible and usable from everywhere (including the journey page), but I want this specific button only on the journey page and nowhere else because, according to the theme of the website (by my team of designers) its supposed to be an aesthetic functionality
What can I do to make this happen? because I've tried re-creating the hook into App.jsx and try passing each func/var as props and then in Journey referencing it as props.sidebar etc. but that doesnt work either....
if the solution is to just pass as parameters, how exactly do I do that because I tried and it said something like it wasnt declared.
Any alternatives?
Thank you,
Solution
- either you lift the state up to their closest common ancestor (app.js) and create a
handleClick
method in App.js (do the state change in App.js) and pass down the method with navBar current state as porps to Journey and NavBar. - or you use a Context check: https://reactjs.org/docs/context.html and https://reactjs.org/docs/hooks-reference.html#usecontext for further info.
Answered By - Abdelaziz Alsabagh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.