Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  53] [ 1]  / answers: 1 / hits: 22432  / 5 Years ago, mon, may 20, 2019, 12:00:00

I have an input text field . When a user inputs any text and clicks enter button I need to activate the blur event to remove the focus and also to validate the textinput .


<input type="text" 
style={{marginTop:'20%', marginLeft:'40%'}}
value={value}
onFocus={onFocus}
onChange={e => setValue(e.target.value)}
onKeyPress={handleKeyPress}
/>

More From » reactjs

 Answers
16

Use refs and this.inputRef.current.blur().This is working solution.





class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.state = {
value:
};
}
keypressHandler = event => {
if (event.key === Enter) {
this.setState({ value: this.inputRef.current.value });
this.inputRef.current.blur();
this.inputRef.current.value = ;
}
};
render() {
return (
<div>
<label>Enter Text</label>
<input
type=text
ref={this.inputRef}
onKeyPress={event => this.keypressHandler(event)}
/>
<p>{this.state.value}</p>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));

<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' />




[#52095] Tuesday, May 14, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;