Home > database >  How to call a function in another component from a different component in react js?
How to call a function in another component from a different component in react js?

Time:05-11

I having two files header.js and upload.js. In upload.js I have a popup modal which should be open when I click upload button in the header.js

So basically I want to call setOpened function present in upload.js from header.js

header.js

import React from 'react'

const Header = () => {
  return (
    <div>
          <Link
             data-bs-toggle="modal"
             onClick={() => setOpened(true)}
             role="button"
            >Upload</Link>
    </div>
  )
}

export default Header

upload.js

import React from 'react'
const [opened, setOpened] = useState(false);

const Upload = () => {
  return (
    <div>
      <Modal
        opened={opened}
        onClose={() => setOpened(false)}
        title="Introduce yourself!"
      >
        {/* Modal content */}
      </Modal>
    </div>
  )
}

export default Upload

In App.js

import Header from './component/Header';
import Footer from './component/Footer';
import Upload from './component/Upload';

function App() {
  return (
   <Header/>
       <Routes>
         <Route path="/upload" element={<Upload/>}/>
       </Routes>
   <Footer/>
);
}

export default App;

CodePudding user response:

To echo @I-vasilich-I's comment about lifting state up, you should move your modal open state to a higher level (like in App) and pass that state to each child that needs it.

For example

const Header = ({ openModal }) => (
  <div>
    <Link data-bs-toggle="modal" onClick={openModal} role="button">
      Upload
    </Link>
  </div>
);

const Upload = ({ opened, closeModal }) => (
  <div>
    <Modal opened={opened} onClose={closeModal} title="Introduce yourself!">
      {/* Modal content */}
    </Modal>
  </div>
);

const App = () => {
  const [opened, setOpened] = useState(false);
  return (
    <>
      <Header openModal={() => setOpened(true)} />
      <Routes>
        <Route path="/upload" element={<Upload opened={opened} closeModal={() => setOpened(false)} />} />
      </Routes>
      <Footer />
    </>
  );
};

(note make sure you add imports)

  • Related