skip to Main Content

I have a button component which when clicked should render a modal to the screen, but for some reason it seems not to work, here’s my implementation

import React, { useCallback } from 'react';
import { OverflowMenuItem } from '@carbon/react';
import { useTranslation } from 'react-i18next';
import { AddItemToListModal } from '@myLib/commons-lib';

const AddToListOverflowMenuItem = ({ patientUuid }) => {
  const { t } = useTranslation();
  const handleClick = useCallback(() => AddItemToListModal, []);

  return (
    <OverflowMenuItem
      itemText={t('addToList')}
      onClick={handleClick}
      style={{
        maxWidth: '100vw',
      }}
    />
  );
};

export default AddToListOverflowMenuItem;

2

Answers


  1. The problem is how you declare and use your function inside the useCallback. You’re doing it wrong.

    To make it work, simply change your useCallback to be like this:

    const handleClick = useCallback(() => {
     AddItemToListModal();
    }, []);
    

    The useCallback first argument explanation:

    fn: The function value that you want to cache. It can take any
    arguments and return any values. React will return (not call!) your
    function back to you during the initial render. On next renders, React
    will give you the same function again if the dependencies have not
    changed since the last render. Otherwise, it will give you the
    function that you have passed during the current render, and store it
    in case it can be reused later. React will not call your function. The
    function is returned to you so you can decide when and whether to call
    it.

    For more information:
    https://react.dev/reference/react/useCallback

    Login or Signup to reply.
  2. const AddToListOverflowMenuItem = ({ patientUuid }) => {
            const { t } = useTranslation();
            const handleClick = useCallback(() => AddItemToListModal, []);
            const [isVisible, setIsVisible] = useState(false);
    
            return (
                <React.Fragment>
                    <OverflowMenuItem
                        itemText={t('addToList')}
                        onClick={() => setIsVisible(true)}
                        style={{
                            maxWidth: '100vw',
                        }}
                    />
                    <AddItemToListModal isVisible={isVisible} />
                </React.Fragment>
            );
        };
    
        export default AddToListOverflowMenuItem;
    

    With modal I’d normally work with some isVisible state that is set locally like that.. a modal can/should already be nested in the tree. This is just a basic example to show.. you’ll need to device how to hide and handle this prop inside your modal component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search