Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A better way to make hooks available to children in React with TS?

I have a component structure like this:

Modal
  ModalTitle
  ModalBody
    FormElements
      MySelect
      MyTextField
      MyCheckbox
    DisplayInfo
  ModalActions

and a state variable, formVars, and a function that updates it, handleAction, that I need to use basically everywhere. The only way I know how to get this working is by sending it as an attribute to every component. Is there a way to make it available to everything under Modal?

Here’s how I’m sending it now:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// FormElements.tsx
switch(elementType){
  case 'text': return <MyTextField formVars={formVars} handleAction={handleAction} />
  case 'select': return <MySelect formVars={formVars} handleAction={handleAction} />
  case 'checkbox': return <MyCheckbox formVars={formVars} handleAction={handleAction} />
}

And I’m wondering if there’s an easier way to make formVars and handleAction available to all the children of Modal?

>Solution :

Check on the official React documentation about how to create your own hook. By creating this file and passing it to your components you have easy access to these attributes everywhere.

To create your own hook, create a file and name it as you want.

import { useState } from 'react';

function useModalParams(friendID) {
  const [formVars, setFormVars] = useState(null);
  const [handleAction, setHandleAction] = useState(null);

  return {formVars, setFormVars, handleAction, setHandleAction};
}

After that you can use it like this:

import React, { useState, useEffect } from 'react';

function Modal(props) {
  const {formVars, setFormVars, handleAction, setHandleAction} = useModalParams;

  return (

  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading