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

Time:07-30

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:

// 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?

CodePudding user response:

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 (

  );
}
  • Related