Home > OS >  How do I pass a UseState to another jsx component?
How do I pass a UseState to another jsx component?

Time:06-16

I am working on a react Movie app and I want to pass a showModal useState to another component as I have a conditional on the component with my showModal like this:

 const [showModal, setShowModal] = useState(false);
  return (
    <>
      {showModal ? (<div>Modal..</div>) : null}

    </>

Then on the other component I want to pass the hook to is something like this:

...   <button
        type="button"
        onClick={() => setShowModal(true)}
        className="my-4 border text-white py-2 px-4 rounded-3xl border-blue-600 bg-blue-600 shadow-lg"
      >
        Watch trailer
      </button>...

Thanks in advance!

CodePudding user response:

You can totally pass the setShowModal as a props.

 const [showModal, setShowModal] = useState(false);
   return (
    <>
     {showModal ? (<Modal setShowModal={setShowModal} />) : null}

    </>

CodePudding user response:

Write this hook : const [showModal, setShowModal] = useState(false); in the parent component.
And then pass the function setShowModal in props of your modal componant.
export default function YourModal({setShowModal}){
}

Your modal component should look like this and you can use the function setShowModal inside this component

CodePudding user response:

Well the best approach here is to use react context api , since you don't write your code base and components tree it's very difficult to guess which one belongs to other! Anyway you could have this kind of context called modalContext :

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

const ModalContext = createContext(null);

function ModalProvider({ children }) {
  const [showModal, setShowModal] = useState(false);

  return (
    <ModalContext.Provider value={{ showModal, setShowModal }}>
      {children}
    </ModalContext.Provider>
  );
}

function useModal() {
  const context = useContext(ModalContext);
  if (context === undefined) {
    throw new Error('useModal must be used within a ModalProvider');
  }
  return context;
}

export { ModalProvider, useModal };

and then wrap your application with the provider :

import {ModalProvider} from '...(path to context)/modalContext';
<ModalProvider>
  <App />
</ModalProvider>

then where ever you need modalShow or the setter setModalShow you can call it like this easily :

import {useModal} from '..path to /modalContext';

function SomeComponent() {
const {showModal, setShowModal} = useModal();

   return (
      <>
         {showModal ? (
            <ChildComponent toggleModal={setShowModal}>Modal.. 
            </ChildComponent>
         ) : null}
      </>
      );
}

  • Related