score:155
You could use the ref
prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.
In your render
method:
<input ref={input => this.inputElement = input} ... />
In your event handler:
this.inputElement.click();
Full example:
class MyComponent extends React.Component {
render() {
return (
<div onClick={this.handleClick}>
<input ref={input => this.inputElement = input} />
</div>
);
}
handleClick = (e) => {
this.inputElement.click();
}
}
Note the ES6 arrow function that provides the correct lexical scope for this
in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById
, i.e. the actual DOM-node.
score:-3
How about just plain old js ? example:
autoClick = () => {
if (something === something) {
var link = document.getElementById('dashboard-link');
link.click();
}
};
......
var clickIt = this.autoClick();
return (
<div>
<Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
</div>
);
score:0
If it doesn't work in the latest version of reactjs, try using innerRef
class MyComponent extends React.Component {
render() {
return (
<div onClick={this.handleClick}>
<input innerRef={input => this.inputElement = input} />
</div>
);
}
handleClick = (e) => {
this.inputElement.click();
}
}
score:0
imagePicker(){
this.refs.fileUploader.click();
this.setState({
imagePicker: true
})
}
<div onClick={this.imagePicker.bind(this)} >
<input type='file' style={{display: 'none'}} ref="fileUploader" onChange={this.imageOnChange} />
</div>
This work for me
score:0
let timer;
let isDoubleClick = false;
const handleClick = () => {
if(!isDoubleClick) {
isDoubleClick = true;
timer = setTimeout(() => {
isDoubleClick = false;
props.onClick();
}, 200);
} else {
clearTimeout(timer);
props.onDoubleClick();
}
}
return <div onClick={handleClick}></div>
score:0
this.buttonRef.current.click();
score:0
for typescript you could use this code to avoid getting type error
import React, { useRef } from 'react';
const MyComponent = () => {
const fileRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
fileRef.current?.focus();
}
return (
<div>
<button onClick={handleClick}>
Trigger click inside input
</button>
<input ref={fileRef} />
</div>
);
}
score:2
Try this and let me know if it does not work on your end:
<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>
Clicking on the div
should simulate a click on the input
element
score:5
Using React Hooks and the useRef
hook.
import React, { useRef } from 'react';
const MyComponent = () => {
const myInput = useRef(null);
const clickElement = () => {
// To simulate a user focusing an input you should use the
// built in .focus() method.
myInput.current?.focus();
// To simulate a click on a button you can use the .click()
// method.
// myInput.current?.click();
}
return (
<div>
<button onClick={clickElement}>
Trigger click inside input
</button>
<input ref={myInput} />
</div>
);
}
score:6
Riffing on Aaron Hakala's answer with useRef inspired by this answer https://stackoverflow.com/a/54316368/3893510
const myRef = useRef(null);
const clickElement = (ref) => {
ref.current.dispatchEvent(
new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
}),
);
};
And your JSX:
<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>
score:8
In a functional component this principle also works, it's just a slightly different syntax and way of thinking.
const UploadsWindow = () => {
// will hold a reference for our real input file
let inputFile = '';
// function to trigger our input file click
const uploadClick = e => {
e.preventDefault();
inputFile.click();
return false;
};
return (
<>
<input
type="file"
name="fileUpload"
ref={input => {
// assigns a reference so we can trigger it later
inputFile = input;
}}
multiple
/>
<a href="#" className="btn" onClick={uploadClick}>
Add or Drag Attachments Here
</a>
</>
)
}
score:9
You can use ref
callback which will return the node
. Call click()
on that node to do a programmatic click.
Getting the div
node
clickDiv(el) {
el.click()
}
Setting a ref
to the div
node
<div
id="element1"
className="content"
ref={this.clickDiv}
onClick={this.uploadLogoIcon}
>
Check the fiddle
https://jsfiddle.net/pranesh_ravi/5skk51ap/1/
Hope it helps!
score:24
Here is the Hooks solution
import React, {useRef} from 'react';
const MyComponent = () =>{
const myRefname= useRef(null);
const handleClick = () => {
myRefname.current.focus();
}
return (
<div onClick={handleClick}>
<input ref={myRefname}/>
</div>
);
}
score:31
Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html
import React, { Component } from "react";
class AddImage extends Component {
constructor(props) {
super(props);
this.fileUpload = React.createRef();
this.showFileUpload = this.showFileUpload.bind(this);
}
showFileUpload() {
this.fileUpload.current.click();
}
render() {
return (
<div className="AddImage">
<input
type="file"
id="my_file"
style={{ display: "none" }}
ref={this.fileUpload}
/>
<input
type="image"
src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
width="30px"
onClick={this.showFileUpload}
/>
</div>
);
}
}
export default AddImage;
Source: stackoverflow.com
Related Query
- How to manually trigger click event in ReactJS?
- How do I trigger a click event based on a specific className in ReactJS
- How to trigger INPUT FILE event REACTJS by another DOM
- how trigger event parent to child in Reactjs
- How to select text to copy without triggering click event in reactjs
- React-Router Link, how to trigger a click event on a Link from another component
- How to set state and props on a single click event in reactjs
- how to handle array of buttons handle click event in ReactJs
- How to remove object from Array in ReactJS after click event
- How to disable click event while fetching the data in reactjs witout jquery?
- how to trigger a click event by specifying coordinate position(x,y) in react?
- How to add the click event on the icons in reactjs
- In React how can I trigger a custom button's click event from a different compoennt's event handler?
- How to fire a click event in a ul, li or div in reactjs
- How to properly display loading event on button click using reactjs
- Auto trigger click event handler on last element of array map. Reactjs
- how to handle the click event to display text in the <span> tag on reactjs
- How to pending button show approved on click event by reactjs
- How to get input text value on click in ReactJS
- How to get pasted value from Reactjs onPaste event
- How to trigger keypress event in React.js
- How do I trigger a change event on radio buttons in react-testing-library?
- How to detect Click + [Shift, Ctrl, Alt] in reactjs click event?
- How do I trigger the change event on a react-select component with react-testing-library?
- Material-ui: How to stop propagation of click event in nested components
- ReactJS: how to trigger form submit event from another event
- How to trigger onChange on <input type='file' /> by another Button click in ReactJS?
- how to add row to a table using ReactJS on button click
- How to call multiple functions on the same onClick event ReactJS
- Trigger onblur event on click of enter keypress in React js
More Query from same tag
- React Testing Library - Mock Service Worker response not used by component
- How to transfer state between React components with hooks?
- JS,HTML Form I want to make preview and preview image size pix
- this.setState isn't working (my state is a number)
- React conditional rendering of JSX
- Where do I use my string to numerical function in my OrderBy function?
- How can I change state of object in a React list onClick?
- How to pass component to props using React TypeScript?
- Why is my onChange event not working in React?
- React without npm
- How to pass function with React Hooks?
- Ant design tab title style issues
- REACT - Clicking on Resume header doesn't download resume pdf file
- How update local storage in all opened tab
- Bootstrap collapse with react js
- React - Subsequent variable declarations must have the same type
- How to substr item in array
- ReactJS: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state
- Updating dropdown from redux state in componentDidMount()
- How to add passive event listeners in React?
- Can't Edit and Update properties with form Reactjs and MongoDB
- How to store values in react, that are not state changing?
- How to test HOC using react testing library
- Material UI Select - object as value fails
- When is it necessary to use `rerender` with the React Testing Library?
- How do I add more number of rows at a time?
- Updating state from child component reactjs
- How to filter out multiple objects values including nested object value with matching string?
- Code optimization in Reactjs for multiple events
- react-draft-wysiwyg - Prevent drag and drop text if max-length exceed