Excuse the silly title :)
I have a button which when clicked runs a function called restart
which simply resets a state. I want to make this button easily accessible, so when you press the tab, the button highlights prompting you to either press enter or click it.
basic code
class Home extends Component{
restart(){
this.setState({popup:false,finished:true,started:false,userInput:""})
}
render(){
return(
<div>
<button className="btn btn-dark buttons" onClick={this.restart.bind(this)}>Restart</button>
</div>
)
}
Everything works fine if you click the button, but when pressing Enter
, the page is reloaded which is quite harmful.
How might I be able to disable this reload when the button is submitted using the Enter
key, and still call the restart
method.
The easiest way is to use a form
and call your restart
method on the onSubmit
event. This way it's accessible for keyboard users as well. Don't forget to call event.preventDefault()
to not to reload the page.
Check out the demo below:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { popup: true, finished: false, started: true, userInput: '' };
this.restart = this.restart.bind(this);
}
restart(e) {
// make sure you don't reload the page
e.preventDefault();
this.setState({
popup: false,
finished: true,
started: false,
userInput: '',
});
}
render() {
return (
<form onSubmit={this.restart}>
<button className="btn btn-dark buttons" type="submit">
Restart
</button>
<pre>
{JSON.stringify(this.state, null, 2)}
</pre>
</form>
);
}
}
ReactDOM.render(<Home />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>