I need a button inside a form which triggers the onSubmit
event when user presses the Enter button.
This is the example of a working solution:
<form onSubmit={() => console.log('ok')}>
<button type="submit" autoFocus>Submit</button>
</form>
When the user presses Enter, onSubmit
is properly triggered.
My problem is when I have to render this button in render props of a component:
<Component render={()=> (
<button type="submit" autoFocus /> // here the button will not be focused
)}/>
So when I press Enter, nothing happens.
Is there any way to get a working solution using only html attributes?
CodePudding user response:
It is not working because in your example the button onClick
event is not connected to the GoogleLogin
or the wrapping Component
.
Step by step:
Because of the autoFocus
, when your button is rendered it is automatically focused. As soon as you click enter
while it is still focused the click event of that button is fired.
In the pure html
example the onSubmit
of the form is triggered because the button has a type="submit"
.
<form onSubmit={() => console.log('ok')}>
<button type="submit" autoFocus>Submit</button>
</form>
So if you want your example to trigger the GoogleLogin
on click of enter
, you have to trigger it manually trough props on click of your button like that:
<GoogleLogin
render={(renderProps) => (!renderProps.disabled ?
<button autoFocus onClick={renderProps.onClick}>
This is my custom Google button
</button>: null
)}
/>
Keep in mind, if the user clicks Tab, the autofocus will be lost and the enter
input will not trigger the onClick
event anymore.
Instead, you could set up an event listener which will listen for the enter
input and trigger GoogleLogin as long as it is rendered, independently of the autoFocus. Or you let your user click that button instead of enter.