I'm very new to ReactJS and I'm just trying to do some small things to understand more.
I was wondering if the OnKeyPress can trigger a button press. I've seen a few similar questions but what the OnKeyPress triggered was just a console.log or an alert. So I wasn't sure how to trigger the button press.
This is what I have so far:
class Form extends React.Component {
onButtonPress = (e) => {
// this is just an example of what happens when the button is pressed.
this.setState({isClicked: true});
}
keyPress = (event) => {
if (event.key == 'Enter'){
// How would I trigger the button that is in the render? I have this so far.
this.onButtonPress();
}
}
render() {
return (
<div>
<div className="fieldForm">
<input
value={name}
type="name"
onKeyPress={this.keyPress}
/>
</div>
<Button onClick={this.onButtonPress}>Submit</Button>
</div>
)
}
}
Please note that I didn't include everything in here such as the constructor, props, or the state object attributes.
The purpose of this is to make it look like the button has been clicked. When the button is clicked, it'll show a small loading sign on the button. I want the same thing to happen if I were to press enter (with the loading sign on the button, that's why I want the button pressed).
Is this possible?
Programmatically triggering DOM events is not something you should do unless you have very specific needs.
Both onKeyPress and onClick are event handlers, you can do anything you want when an event happens. I would just call a function that sets the state you want from both handlers.
Here's an example:
class Form extends React.Component {
handleFormSubmit = () => {
this.setState({ isClicked: true });
};
handleButtonPress = () => {
this.handleFormSubmit();
};
handleKeyPress = event => {
if (event.key == 'Enter') {
this.handleFormSubmit();
}
};
render() {
return (
<div>
<div className="fieldForm">
<input value={name} type="name" onKeyPress={this.handleKeyPress} />
</div>
<Button onClick={this.handleButtonPress} loading={this.state.Load}>
Submit
</Button>
</div>
);
}
}
In case you have no other way and you should click on this element for some vague reason and the method that elas said didn't work for you. try this:
onButtonPress = (e) => {
console.log('hi hi')
}
handleKeyPress = (event) => {
if (event.key === 'Enter') {
this.refs.but.click()
}
}
render () {
return (
<Layout>
<div>
<div className="fieldForm">
<input
value={'name'}
type="name"
onKeyPress={(e) => this.handleKeyPress(e)}
/>
</div>
<Button onClick={this.onButtonPress} ref="but">Submit</Button>
</div>
</Layout>
)
}
Related
i've got a problem that don't know how to deal with. I'm using HCaptcha component for verification and after the user clicks on the checkbox in order to verify, my 'keydown' eventListener does not work anymore. apparantly the problem is that HCaptcha is rendering in iframe and the page loses focus after checking it.
Any one got any ideas? Thanks for your help.
useEffect(() => {
const listener = event => {
if (event.code === 'Enter' || event.code === 'NumpadEnter') {
event.preventDefault();
btnRef.current?.click();
}
};
document.addEventListener('keydown', listener);
return () => {
document.removeEventListener('keydown', listener);
};
}, []);
return (
<div className="auth-footer">
<HCaptcha
sitekey={window._env_.hCaptchaSiteKey}
onVerify={token => {
setCapchaToken(token);
formRef.current?.focus();
}}
ref={captchaRef}
/>
<div className="tw-my-6">
<Button
ref={btnRef}
type="button"
disabled={formValidation()}
onClick={handleSubmit}
loading={loading}
className="btn reset-password-submit">
ارسال کد
</Button>
</div>
</div>
)
Code:
const Component = () => {
const[divShow, setDivShow] = useState(false);
const toggleDivShow = () => {
setDivShow(!divShow)
}
return (
<div>
<button onClick={toggleDivShow}>
{
divShow && <div>click the button to show me</div>
}
</div>
)
}
now, this is working perfectly and toggle showing the div when the user click the button but, this only hide the div when the user click the button, How to hide the div when the user click anywhere else in the window
I tried to add a click event listener to the window that set divShow to false but unfortunately this didn't work, as this affected the button too and divShow always set to false even when i click the button, this is expected i think because the button is a part of the window
How can i solve this problem??
add divShow to useEffect dependency array, also dont forget to call clean up method in useEffect, as multiple document.addEventListener will cause the browser to hang.
const Component = () => {
const [divShow, setDivShow] = useState(false);
const toggleDivShow = () => {
setDivShow(!divShow);
};
useEffect(() => {
if(divShow){document.addEventListener("click", toggleDivShow)}
return () => document.removeEventListener("click", toggleDivShow); //cleaning the side effect after un-mount
}, [divShow]);
return (
<div>
<button onClick={toggleDivShow}>
{divShow && <div>click the button to show me</div>}
</button>
</div>
);
};
I want to display a custom warning message when <input type='file'...> is clicked, and then let a browser starts a file-selection dialog with clicking 'Confirm' button. This is to make sure users aware of the warning message correctly. Is it possible?
import React from "react";
import "./styles.css";
export default function App() {
const [warn, setWarn] = React.useState(false);
const inputRef = React.useRef();
const handleChange = e => {};
const handleClick = e => {
if (!warn) {
setWarn(true);
e.preventDefault();
}
};
const handleContinue = e => {
const event = new Event("input", { bubbles: true });
inputRef.current.dispatchEvent(event);
};
return (
<div className="App">
{warn ? (
<div>
<h1>WARNING MESSAGE...</h1>
<button onClick={handleContinue}>Confirm</button>
</div>
) : (
""
)}
<label htmlFor="test-input">
<input
id="test-input"
ref={inputRef}
type="file"
onChange={handleChange}
onClick={handleClick}
/>
</label>
</div>
);
}
When input is clicked, check if click event was triggered by the browser or via a script. Event.isTrusted will be true when click event is triggered by the browser, so in this case use Event.preventDefault() to prevent file dialog from opening.
Then write the code that does what you want to do and finally call event.target.click() to trigger the click event again but this time Event.isTrusted will be false, so file dialog will not be prevented from opening.
Keep in mind that code you want to execute, before the file dialog is opened, should be in the else block. Otherwise, it will execute two times.
const input = document.querySelector('input');
input.addEventListener('click', (e) => {
if (e.isTrusted) {
e.preventDefault();
} else {
console.log('doing something....');
console.log('done. Opening file dialog');
}
e.target.click();
})
<input type="file"/>
You can trigger the file picker with input.click() but that will also change event.isTrusted to false since it wasn't triggered manually by a user interaction
picker.onclick = evt => {
evt.isTrusted && evt.preventDefault(confirm('are you sure?') && evt.target.click())
}
<input id="picker" type="file">
`
I have a trigger button that will open a dialog asking if a user would like to enable text to speech. Once the dialog is open, I want to focus on the yes button within the dialog by getting the button element by its ID.
When the trigger is pressed, the following function is called:
private openTTSDialog = () => {
if (this.state.ttsDialog === true) {
this.setState({ ttsDialog: false })
} else {
this.setState({ ttsDialog: true }, () => {
// search document once setState is finished
const yesButton = document.getElementById('tts-dialog-yes-button')
log('yesButton', yesButton)
if (yesButton) {
yesButton.focus()
}
})
}
}
And my dialog is conditionally rendered with a ternary expression like this:
{
this.state.ttsDialog ? (
<div className="tts-dialog-container">
<div className="tts-dialog-text-container">
{session.ttsEnabled ? (
<div>
{
strings.disableTTS
}
</div>
) : (
<div>
{
strings.enableTTS
}
</div>
)}
</div>
<div className="tts-dialog-button-container">
<button
aria-label={strings.yes}
tabIndex={0}
className="tts-dialog-button"
id="tts-dialog-yes-button" // this is the button I want to focus
onClick={this.toggleTTS}
>
{
strings.yes
}
</button>
<button
aria-label={strings.no}
tabIndex={0}
className="tts-dialog-cancelButton"
onClick={this.closeTTSDialog}
>
{
strings.no
}
</button>
</div>
</div>
) : null
}
My log for yesButton is undefined. I thought adding the callback function to setState would fix this because I would be searching the document after setState was finished, but I'm still missing something. Any idea what it is?
In the constructor of your class, you should add a ref to your button:
this.myRef = React.createRef();
Then in your button :
<button
ref={this.myRef}
aria-label={strings.yes}
tabIndex={0}
className="tts-dialog-button"
id="tts-dialog-yes-button" // this is the button I want to focus
onClick={this.toggleTTS}
>
Finally, instead of doing:
const yesButton = document.getElementById('tts-dialog-yes-button')
You should do :
const yesButton = = this.myRef.current;
Actually I would also think this should work since you use a callback on setState, so the new render should have completed and the element should already be mounted and accessible. Anyway I think the idiomatic React way for this would be to use a ref (https://reactjs.org/docs/refs-and-the-dom.html) and put it on the button like <button ref={this.yesButton} ...>...</button> and then call this.yesButton.focus(). Have you tried that already?
React prevent form submission when enter is pressed
I have the following React Search Bar component where the parent container can call using
<SearchBar onInputChange={this.handleInputChange} />
Everytime the user changes the input, the parent container will be notified. This is why my search bar does not need any submit button.
However, I am finding that if I press enter inside my search bar, the whole page refreshes. And I dont want that.
I know if I have a button in the form, I could call event.preventDefault(). But in this case I have no button so I dont know what to do here
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.setState({ value: e.target.value });
this.props.onInputChange(e.target.value);
}
render() {
return (
<div id="search-bar">
<form>
<FormGroup controlId="formBasicText">
<FormControl
type="text"
onChange={this.handleChange}
value={this.state.value}
placeholder="Enter Character Name"
/>
</FormGroup>
</form>
</div>
);
}
}
export default SearchBar
You need to create a form handler that would prevent the default form action.
The simplest implementation would be:
<form onSubmit={e => { e.preventDefault(); }}>
But ideally you create a dedicated handler for that:
<form onSubmit={this.submitHandler}>
with the following implementation
submitHandler(e) {
e.preventDefault();
}
In a React component with a Search input field, nested in a larger (non-React OR React) form, this worked best for me across browsers:
<MyInputWidget
label="Find"
placeholder="Search..."
onChange={this.search}
onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}
value={this.state.searchText} />
(e)=>{e.target.keyCode === 13} (#DavidKamer's answer) is incorrect: You don't want the event.target. That's the input field. You want the event itself. And in React (specifically 16.8, at the moment), you want event.key (e.key, whatever you want to call it).
I'm not sure if this works for every situation, as when you press enter in a form's input field you will still trigger the onSubmit method, although the default submit won't occur. This means that you will still trigger your pseudo submit action that you've designed for your form. A one liner with ES6 that solves the problem specifically and entirely:
<input onKeyPress={(e)=>{e.target.keyCode === 13 && e.preventDefault();}} />
This solution should have 0 side effects and solves the problem directly.
The best way to prevent the ENTER, as suggested also by Eon is to add the following to your input element:
onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}
This works for me:
<Input
...
onKeyDown={(e) => { e.key === 'Enter' && e.preventDefault() }}
/>
prevent for Enter key for search input:
<input type="text" onKeyPress={e => {
if (e.key === 'Enter') e.preventDefault();
}} />