8

I try to access some refs in my component. But I have this error in the console. withRouter.js:44 Warning: Stateless function components cannot be given refs (See ref "pseudo" in FormInputText created by RegisterForm). Attempts to access this ref will fail.

Here is my component:

class RegisterForm extends React.Component {

  render() {
    return (
      <form action="">
        <FormInputText ref="pseudo"  type="text" defaultValue="pseudo"/>
        <input type="button" onClick={()=>console.log(this.refs);} value="REGISTER"/>
      </form>
    );
  }
}

Plus when I click on the button I got Object {pseudo: null}in the console. I would expect an object instead null.

I am not sure to understand why this is not working. Note that my react tree uses mobx-react.

dagatsoin
  • 2,626
  • 6
  • 25
  • 54
  • Possible duplicate of [React stateless component this.refs..value?](http://stackoverflow.com/questions/37266411/react-stateless-component-this-refs-value) – Inanc Gumus Jan 24 '17 at 10:04

2 Answers2

13

Refs do not work with stateless components. It is explained in the docs

Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component.

Stateless components at the moment of writing actually have instances (they are wrapped into classes internally) but you can not access them because React team is going to make optimizations in the future. See https://github.com/facebook/react/issues/4936#issuecomment-179909980

Konstantin
  • 24,271
  • 5
  • 48
  • 65
  • Yes I read that. So I am not sure what is a stateless, since I though using a class automatically create a state. – dagatsoin Jul 27 '16 at 17:29
  • Plus, there is no state in the exemple. Is it ? https://facebook.github.io/react/docs/more-about-refs.html#a-complete-example – dagatsoin Jul 27 '16 at 17:30
  • @DanielN the link also explains what stateless component is – Konstantin Jul 27 '16 at 17:30
  • @DanielN post `FormTextInput` code, please. I am pretty sure it is a function, not a class – Konstantin Jul 27 '16 at 17:31
  • Stateless functional components _can_ use callback refs in the render function to _internally_ access the DOM: http://stackoverflow.com/a/40795623/60647 – mwigdahl Jan 19 '17 at 15:51
1

You could also try using recompose it has a function called toClass.

Takes a function component and wraps it in a class. This can be used as a fallback for libraries that need to add a ref to a component, like Relay.

If the base component is already a class, it returns the given component.

Community
  • 1
  • 1
Julius Breckel
  • 434
  • 3
  • 14