Home > Software engineering >  How to call an existing onclick function outside component?
How to call an existing onclick function outside component?

Time:10-22

I have an onclick function for my menu bars in my Navbar.js component and I want to call it in my App.js so that I could move some specific pages in my website to the right when I toggle the menu bars.

Here's my App.js, the route inside div with the className of mainpage is the route/page I want to move whenever I toggle the menubars

function App() {
  
  return (
    
    <AuthProvider>
      <Router>
      <PrivateRoute path="/" component={Navubaru}/>
      <div className="mainpage">
      <Route path="/home" component={Home}/>
      </div>
      </Router>
    <Container className="d-flex align-items-center justify-content-center" style={{ minHeight: "100vh"}}>
      <div className="w-100" style={{maxWidth:'400px'}}>
        <Router>
          <Switch>
            <PrivateRoute exact path="/" component={Dashboard}/>
            <Route path="/signup" component={Signup}/>
            <Route path="/login" component={Login}/>
            <Route path="/forgot-password" component={ForgotPassword}/>
            <Route path="/update-profile" component={UpdateProfile}/>
          </Switch>
        </Router>
      </div>
    
    </Container>
    </AuthProvider>
  )}

export default App

here's my Navbar.js it contains both the sidebar and navbar, It also contains the onClick function im trying to call in App.js:

import React, { useState } from 'react'
import {Navbar, Container} from 'react-bootstrap'
import { Link } from 'react-router-dom';
import { useAuth } from "../contexts/AuthContext"
import './styles/styles.css';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import { IconContext } from 'react-icons';
import { SidebarItem } from './SidebarItem';

export default function Navubaru({component: Component, ...rest}) {
    const { currentUser } = useAuth()
    const [sidebar, setSidebar] = useState(false);

    const showSidebar = () => setSidebar(!sidebar);
    return (
        <div>
            
    <Navbar bg="myColor" variant="dark">
    <IconContext.Provider value={{ color: '#fff' }}>
        <Link to='#' className='menu-bars'>
              <FaIcons.FaBars onClick={showSidebar} />
        </Link>
        <nav className={sidebar ? 'nav-menu active' : 'nav-menu'}>
            <ul className='nav-menu-items' onClick={showSidebar}>
              <li className='navbar-toggle'>
                <Link to='#' className='menu-bars'>
                  <AiIcons.AiOutlineClose />
                </Link>
              </li>
              {SidebarItem.map((item, index) => {
                return (
                  <li key={index} className={item.cName}>
                    <Link to={item.path}>
                      {item.icon}
                      <span>{item.title}</span>
                    </Link>
                  </li>
                );
              })}
            </ul>
          </nav>
        
    
    
    </IconContext.Provider>
    <Container>
    <div className={sidebar ? 'navactive':'navclose'}>
    <Navbar.Brand href="/">Customer Intelligence System</Navbar.Brand>
    </div>
    <Navbar.Toggle />
    <Navbar.Collapse className="justify-content-end">
      <Navbar.Text>
        Signed in as: <a href="/">{currentUser && currentUser.email}</a>
      </Navbar.Text>
    </Navbar.Collapse>
    </Container>
    </Navbar>
    </div>
    )
}

CodePudding user response:

just export the function and then import by name in App.js

eg:

//NavBar.js
export const showSidebar = () => setSidebar(!sidebar);

//App.js
import { showSidebar } from ./path/to/NavBar.js

then do whatever you want

Also as a note, the proper way to update state which references previous state is by using a callback.

export const showSidebar = () => setSidebar((oldState) => !oldState)

https://reactjs.org/docs/hooks-reference.html#functional-updates

CodePudding user response:

It's easy to call any assigned event of one component from another component or file. Here you will need knowledge of these hooks.

useRef()
forwardRef()

Here I've passed this component through forwardRef hook so that I can call any assigned event of this component from another component or file. Like app.js

/**
*
* Navbar.js 
*
*/
import { forwardRef  } from "react";

const Navbar = (props, ref) => {

  const onClickHandler = () => {
     alert('clicked the inner button');
  }

 return (
    <button onClick={onClickHandler} ref={ref} {...props}>  Inner Component Button </button>
   )
}

export default forwardRef( Navbar )

This is my app.js file where I called the the event by using useRef hook

import { useRef } from "react";
import Navbar from "./Navbar";
const App = () => {
  const buttonRef = useRef(null);
  
  const outerClickHandler = () => {
    if( buttonRef.current ) {
      buttonRef.current.click()
    }
  }
  
  return (
  <div className="App">
    <button onClick={outerClickHandler}> Outer button </button>
       <Navbar ref={buttonRef}/>
  </div>
  );
};
export default App;
  • Related