Home > Mobile >  How to define function with hooks typescript and reactjs
How to define function with hooks typescript and reactjs

Time:05-12

Hi I have a problem to define function with hooks. Typescript throwing errors. At this moment toggle is :"any" and define that is function ()=> void doesn't help. Also I can not use "// eslint-disable-next-line". Thank you for any help.

// close pop up model function //

     const [openJob, setOpenJob]= useState(false)

     const toggle = () => {
     setOpenJob(!openJob);
   }; 

//Passing props to my sec component//

  <MyModal
       closeModal={setOpenJob}
       toggle={toggle}
        />
      )}
    </MyModal>

//my sec component//

export type JobProps={
closeJob?: React.Dispatch<React.SetStateAction<boolean>>
toggle?: any;   <---I have to fix it I can not put "any" 

}

  const MyModal = ({ closeJob, toggle }:JobProps) =>{
   <Component>
   <button onClick={() => closeJob(toggle)}> Close me </button>
 </Component>
  }

CodePudding user response:

The type for toggle you said in the comment is correct.

The error is actually with closeJob since this is the updateState function (the second item in the tuple when calling useState). When you give the updateState a function as parameter, it expects it to be an updater function which is a function that will receive the current state as argument and should return the new state to be saved.

This is why void as result of function is unnacceptable. The type of state is boolean.

I think you can try this closeJob(false) or closeJob(() => false) just like how you would call the updateState function.

CodePudding user response:

Actually I can't understand what you want to acheive by the code in MyModal component because I can't see how would you open the modal in first place ? normally if you're trying to open your Modal from another component you should send openJob and toggle as props to your MyModal component and the code should be somathing like this :

MyModal component

const MyModal = ({ open, toggle }: JobProps) => {
  return (
    <Modal open={open} onClose={toggle} className="mymodal">
      <h1>Text in a modal</h1>
    </Modal>
  );
};

export default MyModal;

The component parent (where you call your modal)

export default function App() {
  const [openJob, setOpenJob] = React.useState<boolean>(false);

  const toggle = () => {
    setOpenJob(!openJob);
  };
  const handleClick = () => {
    setOpenJob(true);
  };

  return (
    <div>
      <Button onClick={handleClick}>Open modal</Button>
      <MyModal open={openJob} toggle={toggle} />
    </div>
  );
}

types.ts

export type JobProps = {
  open?: boolean;
  toggle?: any;
};

I used Modal component from MUI but the logic to solve your problem is the same. Here is a live demo where I tried your code and it's working

https://codesandbox.io/s/eager-microservice-hyq7h2?file=/src/App.tsx

  • Related