Home > Mobile >  How can I pass a value from a function to any component in React?
How can I pass a value from a function to any component in React?

Time:12-05

I want to pass a value which I am receiving in a function like this:

const ViewDetails = item => () => {
   console.log(item);
   toggleModal();
}

I want to pass the item to Modal component like open,onclose which is called in the Main function:

return (
   <Layout title="Dashboard" className="container-fluid">
      {<Modal open={modalStatus} onClose={() => setModalStatus(false)} />}
      <div className="row">
         <div className="col-sm-3">
            <UserLinks />
         </div>
         <div className="col-sm-9">
             <UserInfo />
             {orders ? <PurchaseHistory /> : ""}
         </div>
      </div>
   </Layout>
)

I am expecting to have something like this: {<Modal open={modalStatus} onClose={() => setModalStatus(false)} ***item={item}***/>} so that I can use the values inside item in Modal component.

CodePudding user response:

Consider using context API, it enables you to dispatch the item to your reducer.js file and pull it in your Modal component using StateProvider.js file.

CodePudding user response:

I would like to add more to @GODWIN GODWIN comment in regards context API, by providing a very simple example along with the React docs about Context hook

Generally in practice people tend to wrap providers at App.js, for the sake of simplicity I am going to wrap at index.js file.

src/index.jsx

import React from 'react';
import ReactDOM from 'react-dom/client';

import App from './App'
import { ModalProvider } from './context/ModalContext'

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(
  /**
   * @dev Note everything inside ModalPrivder has access
   * to the values provided, such as open, setOpen
   */
  <ModalProvider>
    <App />
  </ModalProvider>
)

src/context/ModalContext.jsx

import React, {useState, createContext, useContext } from 'react'

/**
 * @dev inside your createContext object you can pass in
 * default values that will be passed in value at provider
 */
export const ModalContext = createContext({
 open: false
})

/**
 * @dev your provider will enable you to access value all your
 * children components. NOTE it will not be able to access your
 * parent components.
 */
export function ModalProvider(props) {
  const [open, setOpen] = useState(false)

  return (
    <ModalContext.Provider value={{ open, setOpen }}>
      {props.children}
    </ModalContext.Provider>
  )
}

src/components/Modal.jsx

import { useContext } from 'react'

function Modal(props) {
  const { open, setOpen } = useContext(ModalContext)

  return (
    <>
      { open ? 
        (<div>
          <p>test</p>
          <>{props.children}</>
          <button onClick={() => setOpen(false)}>Close Close</button>
        </div>) : 
        (<button onClick={() => setOpen(true)}>Open Modal</button>)
      }
    </>
  )
}

export default Modal

src/App.jsx

function App(props) {
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Modal>
        <p> You see content here</p>
      </Modal>
    </div>
  );
}

export default App

I hope this give you a good direction on how to use React's context hook, please note that this is a very basic source code, to understand how props.children works and context hook.

CodePudding user response:

You have to take state for this item. When viewDetails function triggered from inside this function you can set this state with this item afte can be pass this state as a props any component

  • Related