Click event inside of Modal: Cannot read property 'click' of null - javascript

Trying to figure out why my click test event is not working. I applied the same setup for another click event on the same file and it worked.
Using Jest and Enzyme for react js
Goal : click event able to capture the node and test to pass
This is what i have for my test case so far:
Test.js
describe("Test Modal Components and Events ", () => {
let mountingDiv;
let wrapper;
beforeEach(() => {
wrapper = mount(<MemoryRouter keyLength={0} initialEntries={["/add"]} ><Policies {...baseProps} /></MemoryRouter>);
mountingDiv = document.createElement('div');
document.body.appendChild(mountingDiv);
})
test case
it('Test click event on Close - Modal', () => {
ReactModal.setAppElement('body');
wrapper = mount( <ReactModal isOpen></ReactModal>,
{attachTo: mountingDiv}
);
wrapper.setState({
quickFilterModalOpen: false,
})
wrapper.update()
expect(!!document.body.querySelector('.fullmodal')).toEqual(true);
expect(!!document.body.querySelector('.sidemodal_addnew_x')).toEqual(true)
document.querySelector("#closemodal-id").click();
});
Here is file.js
<Modal isOpen={this.state.quickFilterModalOpen} style={descriptionModalStyle}>
<div>
<div className='fullmodal'>
<div className='sidemodal_addnew_x' id="closemodal-id" onClick={this.closeModal}>

modal should be visible for the close button to be clicked. Set quickFilterModalOpen to true and use .find(selector) to find the element to be clicked. (https://airbnb.io/enzyme/docs/api/ReactWrapper/find.html)
wrapper.setState({
quickFilterModalOpen: true,
})
wrapper.update()
wrapper.find("#closemodal-id").simulate("click");

I think that is a binding issue, i will go for the event listener or otherwise go for an approach like
onClick = {this.closeModal.bind(this)} or similar, it depends on your code
Hope it helps

Related

Function firing twice on click in React component

TL/DR: My simple toggle function fires twice when button is clicked.
I'm using useEffect in a React (w/ Next.js) component so that I can target the :root <html> tag for which I need the class to be toggled. The code is the following:
useEffect(() => {
const toggleMode = () => {
const root = document.documentElement;
root.classList.toggle("dark");
console.log("click");
};
const toggleBtn = document.querySelector("#toggle-btn");
toggleBtn.addEventListener("click", toggleMode);
I have the necessary imports, the code is placed inside the main component function before the return, and there's no errors in the console at all.
The only issue is that the function is fired twice every time the button is clicked and I cannot find any reason why or solutions online.
Would really appreciate your help and please let me know if I'm missing any information.
Cheers!
Your problem is coming from registering the event listener in a non-react way.
By registering the listener via
const toggleBtn = document.querySelector("#toggle-btn");
toggleBtn.addEventListener("click", toggleMode);
you are setting up a new listener each time the function is run, even if the DOM is not updated. This could result in multiple listeners being registered and firing simultaneously.
You need to add your listener the react way.
function Component ( props ){
const [ isFirst, setIsFirst ] = useState( true );
const [ toggle, setToggle ] = useState( false );
useEffect(() => {
if( isFirst ) {
setIsFirst( false );
return;
}
document.documentElement.classList.toggle("dark");
}, [ toggle ] );
return <div>
<button id="toggle-btn" onClick = { e => setToggle( !toggle ) } />
</div>
}
I resolved a similar problem in this post: Why does my NextJS Code run multiple times, and how can this be avoided?
Your code should only run once if you disable react strict mode.

Manipulating dom elements dynamically in react?

I am trying to have a button change color when the user clicks it in React. Each button I am trying to add this functionality to is also updating state. How can I interact with styles AND update state when these buttons are clicked? Here's my crude attempt:
Some HTML:
<div className="searchPrivacyContainer">
<p>USERS CAN SEARCH FOR MY PROJECT:</p>
<div className="searchPrivacySelect">
<div
className="searchPrivacyYes"
onClick={
(holdColor,
function () {
setProposal({ ...proposal, searchable: true });
})
}
>
And this is the most basic version of the function I'm trying to bind. Writing the body of the function should be the straightforward part hopefully, I just don't know how to bind it to the div which is already calling another function:
const holdColor = (event) => {
console.log(event.target.style);
};
I think this part isn't not working as you expecting,
onClick = {
(holdColor,
function() {
setProposal({ ...proposal,
searchable: true
});
})
}
Simple test,
function x(ev){console.log('x', ev)}
function y(ev){console.log('y', ev)}
const listener = (x, y)
listener(123)
Look, first one (x) never got called, So, you might wanna do something like this on your listener.
onClick={(ev) => {
holdColor(ev)
setProposal({ ...proposal,
searchable: true
});
}}
EDIT:
see this working example (it might be helpful), https://codesandbox.io/s/eloquent-wilson-drbbk?fontsize=14&hidenavigation=1&theme=dark

React Hooks: useEffect for modal event listener

I have a modal dialog that I want to close if the user clicks outside of the modal. I have written the following useEffect code but I run into following issue:
The modal dialog contains a number of children (React Nodes) and those children might change (e.g. the user deletes an entry of a list). Those interactions trigger my onClick method but as the clicked list item has been removed from the modal, the modal closes even though the click was within the modal.
I thought adding [ children ] at the second parameter for useEffect would cleanup the old effect event listener quick enough that the method does not run again but this is not the case.
I handled the same issue in a class component with a ignoreNextClick-state but there must be a cleaner solution, right?
useEffect( () => {
const onClick = ( event ) => {
const menu = document.getElementById( 'singleton-modal' );
if ( !menu ) return;
// do not close menu if user clicked inside
const targetInMenu = menu.contains( event.target );
const targetIsMenu = menu === event.target;
if ( targetInMenu || targetIsMenu ) return;
onCloseModal();
};
window.addEventListener( 'click', onClick, false );
return () => window.removeEventListener( 'click', onClick, false );
}, [ children ] );
I found a solution that does not require any sort of storing old props.
The useEffect call looks like this:
useEffect( () => {
const onClickOutside = () => onCloseModal();
window.addEventListener( 'click', onClickOutside, false );
return () => window.removeEventListener( 'click', onClickOutside );
}, [] );
Adding the following click listener to the modal directly will stop the window click-listener from being called if the user clicked inside the modal.
<div
className={`modal ${ classes }`}
onClick={event => event.stopPropagation()}
role="presentation"
>
{children}
</div>`
I also added the role presentation to make the modal more accessible and aria-conform.
You can check parent of modal from the event.target.
If the current target is within the modal then return.
You can use closest to do that.
See the following solution.
...
if (event.target.closest( '.singleton-modal' ) || event.target.classList.contains('singleton-modal')) {
return;
}
...

React trouble with event.stopPropagation()

I have two components here, the first one is a table, and I have an on-click event attached to one of the <td>'s in every row that summons a little tooltip-like window:
<td onClick={ () => loadSelectorWindow(p.product_id) }>
{
p.selectorActive &&
<SelectorWindow
cancelWindow={this.cancelSelectorWindow}
product_id={p.product_id}/>
}
</td>
The function bound to the <td> click will search through all products in state and flip a boolean on the selected product to display the tooltip.
loadSelectorWindow = (product_id) => {
this.setState({ products: this.state.products.map( p => {
if (p.product_id == product_id) {
p.variationSelectorActive = true
} else {
p.variationSelectorActive = false
}
return p
})})
}
However, the tooltip also needs a button with a window cancel event linked to it:
// within <SelectorWindow />
<p onClick={ () => {cancelWindow(event)} }> X </p>
This function cycles through state and sets all of the display booleans to false.
cancelSelectorWindow = (event) => {
event.stopPropagation()
this.setState ({ products: this.state.products.map( p => {
p.variationSelectorActive = false
return p
})})
}
Putting breakpoints in the code I can see that the cancel button is correctly calling the cancel function and setting the displayTooltip boolean to false, temporarily. The problem is, the loadSelectorWindow is ALSO getting fired when the cancelWindow button is clicked, and the boolean is set back to true DX.
This is why I attempted to put the event.stopPropagation call in there but obviously something is still calling it. There is no other place in my code that the loadSelectorWindow function is mentioned... Any ideas how I can stop it from getting called?
I forgot to pass event to the cancelWindow callback function. React why is your syntax so confusing sometimes...
Fix:
<p onClick={ (event) => {cancelWindow(event)} }> X </p>
You have one html element nested inside the other, so if you click the inner one then you will receive onClick events for both. So that is what you are getting. You need to redesign the layout of the page so that does not happen.

Simulate click event on react element

The bounty expires in 7 days. Answers to this question are eligible for a +50 reputation bounty.
ajaykools wants to reward an existing answer:
Worth bounty, only way simulate clicks on dynamic elements like svg, g, circle, etc which are generated on page load.
I'm trying to simulate a .click() event on a React element but I can't figure out why it is not working (It's not reacting when I'm firing the event).
I would like to post a Facebook comment using only JavaScript but I'm stuck at the first step (do a .click() on div[class="UFIInputContainer"] element).
My code is:
document.querySelector('div[class="UFIInputContainer"]').click();
And here's the URL where I'm trying to do it: https://www.facebook.com/plugins/feedback.php...
P.S. I'm not experienced with React and I don't know really if this is technically possible. It's possible?
EDIT: I'm trying to do this from Chrome DevTools Console.
React tracks the mousedown and mouseup events for detecting mouse clicks, instead of the click event like most everything else. So instead of calling the click method directly or dispatching the click event, you have to dispatch the down and up events. For good measure I'm also sending the click event but I think that's unnecessary for React:
const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
function simulateMouseClick(element){
mouseClickEvents.forEach(mouseEventType =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
})
)
);
}
var element = document.querySelector('div[class="UFIInputContainer"]');
simulateMouseClick(element);
This answer was inspired by Selenium Webdriver code.
With react 16.8 I would do it like this :
const Example = () => {
const inputRef = React.useRef(null)
return (
<div ref={inputRef} onClick={()=> console.log('clicked')}>
hello
</div>
)
}
And simply call
inputRef.current.click()
Use refs to get the element in the callback function and trigger a click using click() function.
class Example extends React.Component{
simulateClick(e) {
e.click()
}
render(){
return <div className="UFIInputContainer"
ref={this.simulateClick} onClick={()=> console.log('clicked')}>
hello
</div>
}
}
ReactDOM.render(<Example/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
If you don't define a class in your component, and instead you only declare:
function App() { ... }
In this case you only need to set up the useRef hook and use it to point/refer to any html element and then use the reference to trigger regular dom-events.
import React, { useRef } from 'react';
function App() {
const inputNameRef = useRef()
const buttonNameRef = useRef()
function handleKeyDown(event) {
// This function runs when typing within the input text,
// but will advance as desired only when Enter is pressed
if (event.key === 'Enter') {
// Here's exactly how you reference the button and trigger click() event,
// using ref "buttonNameRef", even manipulate innerHTML attribute
// (see the use of "current" property)
buttonNameRef.current.click()
buttonNameRef.current.innerHTML = ">>> I was forced to click!!"
}
}
function handleButtonClick() {
console.log('button click event triggered')
}
return (
<div>
<input ref={inputNameRef} type="text" onKeyDown={handleKeyDown} autoFocus />
<button ref={buttonNameRef} onClick={handleButtonClick}>
Click me</button>
</div>
)
}
export default App;
A slight adjustment to #carlin.scott's great answer which simulates a mousedown, mouseup and click, just as happens during a real mouse click (otherwise React doesn't detect it).
This answer adds a slight pause between the mousedown and mouseup events for extra realism, and puts the events in the correct order (click fires last). The pause makes it asynchronous, which may be undesirable (hence why I didn't just suggest an edit to #carlin.scott's answer).
async function simulateMouseClick(el) {
let opts = {view: window, bubbles: true, cancelable: true, buttons: 1};
el.dispatchEvent(new MouseEvent("mousedown", opts));
await new Promise(r => setTimeout(r, 50));
el.dispatchEvent(new MouseEvent("mouseup", opts));
el.dispatchEvent(new MouseEvent("click", opts));
}
Usage example:
let btn = document.querySelector("div[aria-label=start]");
await simulateMouseClick(btn);
console.log("The button has been clicked.");
Note that it may require page focus to work, so executing in console might not work unless you open the Rendering tab of Chrome DevTools and check the box to "emulate page focus while DevTools is open".
Inspired from previous solution and using some javascript code injection it is also possibile to first inject React into the page, and then to fire a click event on that page elements.
let injc=(src,cbk) => { let script = document.createElement('script');script.src = src;document.getElementsByTagName('head')[0].appendChild(script);script.onload=()=>cbk() }
injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js",() => injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js",() => {
class ReactInjected extends React.Component{
simulateClick(e) {
e.click()
}
render(){
return <div className="UFIInputContainer"
ref={this.simulateClick} onClick={()=> console.log('click injection')}>
hello
</div>
}
}
ReactDOM.render(<ReactInjected/>, document.getElementById('app'))
} ))
<div id="app"></div>
Kind of a dirty hack, but this one works well for me whereas previous suggestions from this post have failed. You'd have to find the element that has the onClick defined on it in the source code (I had to run the website on mobile mode for that). That element would have a __reactEventHandlerXXXXXXX prop allowing you to access the react events.
let elem = document.querySelector('YOUR SELECTOR');
//Grab mouseEvent by firing "click" which wouldn't work, but will give the event
let event;
likeBtn.onclick = e => {
event = Object.assign({}, e);
event.isTrusted = true; //This is key - React will terminate the event if !isTrusted
};
elem.click();
setTimeout(() => {
for (key in elem) {
if (key.startsWith("__reactEventHandlers")) {
elem[key].onClick(event);
}
}
}, 1000);
Using React useRef Hooks you can trigger a click event on any button like this:
export default const () => {
// Defining the ref constant variable
const inputRef = React.useRef(null);
// example use
const keyboardEvent = () => {
inputRef.current.handleClick(); //Trigger click
}
// registering the ref
return (
<div ref={inputRef} onClick={()=> console.log('clicked')}>
hello
</div>
)
}
This answer was inspired by carlin.scott code.
However, it works only with focusin event in my case.
const element = document.querySelector('element')
const events = ['mousedown', 'focusin']
events.forEach(eventType =>
element.dispatchEvent(
new MouseEvent(eventType, { bubbles: true })
)
)

Categories

Resources