Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to blur the input provided in semantic-ui-react?

With mouse click everything works, but I want it to work with keyboard

I want input to be unfocused/blurred when I press downKey while sitting in the input component.

This is my input component

import { Input } from 'semantic-ui-react';

<Input 
  focus={this.state.inputFocus} 
  ref='search'
  placeholder='Search...' />

while going into the input, using keypress, this code helps to focus the input

this.refs.search.focus();
this.setState({ inputFocus: true });

but while going out from the input box, the blinking key indicator isn't removed and the box still appears to be focused,

Tried Code Doesn't Work

this.refs.search.blur(); // generates error
this.setState({ inputFocus: false }); //changes state var but ui isn't changed

Blur Error

Blur Error

like image 963
Sabbiu Shah Avatar asked Feb 24 '18 09:02

Sabbiu Shah


1 Answers

If you really need to manually control the blur / focus, then you can listen to the onKeyDown event and check for the arrow-down code.

When condition is met, you can fire the .blur() event on the event.target or set the state as you like:

  shouldBlur = (e) => {
    if (e.keyCode === 40) {
      e.target.blur();
      // or set the state as you wish
    }
  }

And use this handler like this:

<Input value={value} onKeyDown={this.shouldBlur} onChange={this.handleChange} />

Here is a running example:

const { Input, Ref, Button } = semanticUIReact;

class App extends React.Component {
  state = { value: 'initial value' }
  handleChange = (e, { value }) => this.setState(prev => ({ value }));
  focus = () => {
    this.inputRef.focus();
  }
  shouldBlur = (e) => {

    if (e.keyCode === 40) {
      e.target.blur();
      // or set the state as you wish
    }
  }
  render() {
    const { value } = this.state;
    return (
      <div >
      <div>click the down arrow for blur</div>
      <hr/>
        <Input
          value={value}
          onKeyDown={this.shouldBlur}
          onChange={this.handleChange}
          ref={ref => this.inputRef = ref}
        /> 
        <Button onClick={this.focus}>Focus</Button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/semantic-ui-react.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.css"/>
<div id="root"></div>
like image 159
Sagiv b.g Avatar answered Nov 20 '22 04:11

Sagiv b.g