EDIT: Idk if the guy who helped me thought it was worth making an official answer (and I didn't want to steal his thunder by posting an answer myself) but here's my working solution (see comment section for details): CodePen
I've been struggling to auto-focus()
a div
after a React form is submitted. I've tried using useRef [SO link]/ref [SO link] as well as componentDidMount() [SO link] with no success. I'd like to be able to submit the form, then press Enter to close the div
that appears afterwards. I am able to make the div
appear on form-submit and have it so you can close the div
by clicking on it and pressing Enter, but I want to bypass the need to click on the div
first.
Below is the demonstration of what I'm trying to do. I've commented out my attempts at using useRef
. Please run the code below to get a better visual of my goal.
In summary, how can I make a div
auto-focus after a form submits? Thank you in advance
//import useRef from "https://cdn.skypack.dev/useref@1.4.3";
class MyForm extends React.Component {
constructor(props) {
super(props)
//const myRef = useRef(null);
this.state = { modal_enable: false
}
}
submitForm = (event) =>{
event.preventDefault()
//myRef.current.focus()
this.setState({ modal_enable: true })
};
closeModal = () => {
if (event.key === 'Enter' && event.shiftKey === false) {
this.setState({ modal_enable: false })
}
}
render() {
const { modal_enable } = this.state
return (
<div content>
<form onSubmit ={this.submitForm}>
<input
id='text_entry'
type='text'
placeholder='Cursor remains flashing inside this text box (i.e., focus remains here) after submitting by pressing Enter'
/>
<input type='submit'/>
</form>
{modal_enable && (
<div className="modal_box" onKeyDown={this.closeModal} tabIndex={0} /* ref={myRef} */>
<p>Click inside me and press Enter to make me disappear. How can we make it so you don't have to click inside me first?</p>
</div>
)}
</div>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById("root"));
.modal_box {
border: 1px solid;
}
#text_entry{
width: 650px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>