Home > Blockchain >  Javascript click event listener with react function
Javascript click event listener with react function

Time:11-26

I want to create a custom hook in which I add a click event listener to a DOM element which calls a function defined in a React component which uses a state variable.

I add the event listener, but when I call the function, it does not reflect any state changes, it is always taking the initial state value.

const useCustomHook = (functionDefinedInComponent) => {
  // logic to get the dom element
  element.addEventListener('click', () => functionDefinedInComponent(item)); 
};

const CustomComponent = () => {
  const [state, setState] = useState(...);

  const customFunction = (item) => {
    setState(...); // change the 'state' variable
    // use item and state to do something
  }

  useCustomHook(customFunction);

  return ...;
}

When I click the DOM element to which I added the click event, the customFunction triggers with initial state value. Is there any to solve this?

CodePudding user response:

I meant something like this. you might have to wrap your callback function in React.useCallback as well.

const useCustomHook = (functionDefinedInComponent) => {
  React.useEffect(() => {
     // logic to get the dom element
      element.addEventListener('click', () => functionDefinedInComponent()); 
  }, [functionDefinedInComponent])
 
};

Can you try this out and let me know what sort of problem you get.

CodePudding user response:

You can use a public component like this:

const ClickableComponent = props => {
    const { title, handleClick, component: Component } = props;
    return (
        <Component onClick={handleClick}>{title}</button>
    )
};

export default ClickableComponent;

You can use this component like below:

<ClickableComponent title="your title" handleClick={handleClick} component={<button/> } />
  • Related