skip to Main Content
let clickReactElement = (elem) => {
     const event = new Event('click', { bubbles: true })
     elem.dispatchEvent(event);
     for (key in elem) {
     if (key.startsWith("__reactProps")) {
      elem[key].onClick(event);
     }
}

This code works in the console, but doesn’t work when you run it in the actual code. How do I find the __reactProps or __reactEventHandlers via code?

Please tell me why this is?

Let me tell you the background of the problem: I’m working on a browser plug-in that injects script into the target website (react.js), and part of the script is to manipulate the button on the landing page including clicks. onClick in the __reactPropsxxxx property of the DOM element successfully executed the click, but this only works in the console, I execute the same code in the js file I can’t find the __reactProps or __reactEventHandlers related attributes

2

Answers


  1. Have you tried to use react refs ?

    For example:

    import React from 'react'
    
    const Button = () => {
        const buttonEl = React.useRef()
    
        // Manual click over here (pragmatically)
        buttonEl.current.click()
    
        return <button ref={buttonEl}>Click me </button>
    }
    
    Login or Signup to reply.
  2. This might work for you. Try it out.

    import React from 'react';
    import { findDOMNode } from 'react-dom';
    
    const clickReactElement = (element) => {
    
      const node = findDOMNode (element);
      
      if (node) {
    
        const event = new MouseEvent ('click', { bubbles: true });
        
        node.dispatchEvent (event);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search