I have two component say Navbar and Sidebar which is rendered in App.jsx. I need a method defined inside Sidebar to be accessed in Navbar. This is the code
I have this inside Navbar.jsx
export default function Navbar(props) {
const show = props.myMethod;
return (
<div>
<p>This is a gibberish</p>
<p> onClick={show} </p>
</div>
);
}
I have this inside Sidebar.jsx
export default function Sidebar() {
const myMethod = () => {
alert("Hi!!! I am Collins");
};
return (
<div>
<p>I am feeling good</p>
</div>
);
}
Now in my App.jsx I have
import Sidebar from "./Sidebar";
import Navbar from "./Nabar";
function App() {
return (
<>
<Sidebar />
<Navbar myMethod={myMethod} />
</>
);
}
I tried to pass props to the Navbar where I need the method but it comes out with an error that myMethod is not defined.
I know this is going to be a simple thing but I just started learning react by self teaching.
Thanks in advance!!!
I tried to pass props to the Navbar where I need the method but it comes out with an error that myMethod is not defined. I ensured the necessary things were imported in App.jsx but still the same error
3
Answers
The most simple solution would be to hold the method declaration in
App.js
and then, pass it to it’s child components (sibling) components.Here is the code –
App.js
Sidebar.js
Navbar.js
The code above is calling
<myComponent/>
component and passingpropValue
aspropName
to it.so
propValue
should exist in the component calling<myComponent/>
so that it can be passed as props.In your code you are trying to pass
myMethod
asmyMethod
to<Navbar/>
fromApp
but there is nomyMethod
defined there.You can have a look at React useContext hook
or just declare
myMethod
in the App component then pass it toSideBar
andNavbar
Now you can access it from
Navbar
as you are already doing:You can remove
myMethod
fromSidebar
sinceSidebar
is now receiving the same function asprops.myMethod
.