Semantic-UI-React: Form.Input stateless function cannot be given refs.

✖ CSS ISSUES → Post on https://github.com/Semantic-Org/Semantic-UI

✖ USAGE QUESTIONS → Use these dedicated resources: Docs - http://react.semantic-ui.com Chat - https://gitter.im/Semantic-Org/Semantic-UI-React SO - https://stackoverflow.com/questions/tagged/semantic-ui-react?sort=votes

✔ BUGS → This form is required:

Steps

<Form.Input  ref="name"
    onChange={this.onChange.bind(this)} 
    required autoFocus />
this.ref.name.value = "";

Expected Result

ref.name.value should work.

Actual Result

Warning: Stateless function components cannot be given refs (See ref “name” in FormInput created by Register). Attempts to access this ref will fail.

Version

0.77.1

Testcase

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 20 (7 by maintainers)

Most upvoted comments

@layershifter wrapping it in the Ref component gives you the ref of a div, not the actual input. I think this should be reopened

You can wrap any your component to Ref, it will return a real DOM node.

However, I dont see any need to use refs there. Use controlled components, pass your value with value prop:

<Form.Input value={value} />

For anybody who found this and is looking for a way to get a Form.Input to focus when opening a modal, here is another solution: https://codepen.io/inergy/pen/JvOjYb

I’d like to mention another use case that is to integrate with react-hook-form https://github.com/react-hook-form/react-hook-form/issues/85 This is just a nice-to-have as Form.Field could be used instead

Found this for working with semantic form and react-hook-form: https://codesandbox.io/embed/semantic-ui-react-form-hooks-vnyjh

@Karl-Stefan Form.Input wraps the input in a form field, eg:

<div class="field">
  <label>First Name</label>
  <input type="text" name="first-name" placeholder="First Name">
</div>

Thus, the ref to the first element would be the div, whereas the Input component is only the input element.

Thank you, this allows me to assign a ref to call focus() and automatically get the <div class='ui input'> wrapper, which I was doing manually with a raw input tag. Which is great. But now it’s unclear why <Form.Input> shouldn’t have the same ref functionality as <Input>, i.e. the original issue of this thread?

@snardone the input instance offers a focus method for this purpose. It is a common best practice to offer this method for Input components:

https://react.semantic-ui.com/elements/input#input-example-ref-focus

Ok, here is one.

There is a bug with the way different browser handle auto-filled inputs, and thus an input would seem to be filled to the user but React won’t be notified and your state won’t match the browser’s.

One solution for this is to use uncontrolled components.

I’m sure there are other use cases as well.