Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateless function components cannot be given refs

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.

like image 885
dagatsoin Avatar asked Jul 27 '16 17:07

dagatsoin


People also ask

Can stateless components have functions?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

Why functional components are called stateless?

It is also called “stateless” components because they simply accept data and display them in some form that is they are mainly responsible for rendering UI. It accept properties(props) in function and return html(JSX) It gives solution without using state. There is no render method used in functional components.

What is the difference between stateful and stateless components?

Stateful and Stateless Components In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components.

How do you use REF in functional component react?

To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.


1 Answers

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

like image 87
Alik Avatar answered Sep 23 '22 13:09

Alik