Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access function outside of current component

I`m trying to access a function inside main.js with a button in navbar.js so i can open a drawer which I have inside the main.js component.
Is there a way to do this? Or do i have to use Redux for this?
app.js

<Navbar />
<main />

navbar.js

<Button type="default" onClick={showDrawer}>Send</Button>

main.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const showDrawer = () => {
  setOpen(true);
};

enter image description here

>Solution :

To access the showDrawer function in main.js from navbar.js, you can pass the function as a prop to navbar.js and then call it within the onClick event of the button.

Code:

// main.js
const [open, setOpen] = useState(false)

const showDrawer = () => {
  setOpen(true)
}

return (
  <div>
    <Navbar showDrawer={showDrawer} />
  </div>
)
// navbar.js
const Navbar = (props) => {
  const { showDrawer } = props

  return (
    <Button type='default' onClick={showDrawer}>
      Send
    </Button>
  )
}

Edit:

Based on your comment you can use React.memo to wrap the Navbar component:

// main.js
import Navbar from './Navbar';

const [open, setOpen] = useState(false);

const showDrawer = () => {
  setOpen(true);
};

return (
  <div>
    <Navbar showDrawer={showDrawer} />
  </div>
);
// App.js
import Navbar from './Navbar';

const App = () => {
  return (
    <div>
      <Navbar />
    </div>
  );
};

export default React.memo(App);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading