Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need ref to <input> from semantic-ui-react's Form.Input - which is surrounded by divs in React

I am using semantic-ui-react's Form.Input, which wraps the input in two divs.

This means,

<Form.Input type='password' name='password' id='loginPassword'></Form.Input>

is rendered as follows:

<div class='field'>
  <div class='ui fluid action left icon input'>
   <input type='password' name='password' id='loginPassword' ...>
   <button ...>
  </div>
</div>

I would like to get the ref for the <input/> element, so that I can call focus().

  1. My ref is set to the component when using ref='myRef'
  2. ReactDOM.findDOMNode returns a DOM ref, but the ref is set to the outer div (with class='field').

How do I get a ref to the <input/> element?

BTW, I am using redux, although I don't think that matters

like image 294
mdebeus Avatar asked Mar 05 '18 21:03

mdebeus


1 Answers

Form.Input is just a shorthand for some components that are wrapping an Input. So behind the scenes this:

<Form.Input label='Enter Password' type='password' />

Is the same as this:

<Form.Field>
  <label>Enter Password</label>
  <Input type='password' />
</Form.Field>

semantic-ui-react supports the react ref API for Input, but make sure you are using the current ref API and not the old one:

<Input ref={ref => this.input = ref} />

running example:

const { Input, Button } = semanticUIReact; // import

class App extends React.Component {
  onClick = () => this.input.focus();
  render() {
    return (
      <div>
        <Input ref={ref => this.input = ref} />
        <Button onClick={this.onClick}>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 77
Sagiv b.g Avatar answered Sep 19 '22 23:09

Sagiv b.g