Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Stateless function components cannot be given refs" mean?

I have this:

const ProjectsSummaryLayout = ({projects}) => {    return (       <div className="projects-summary col-md-10">           <h3>Projects</h3>           <ul>               { projects.map(p => <li key={p.id}>{p.contract.client}</li>) }           </ul>       </div>    ) }  const ProjectsSummary = connect(    state => ({projects: state.projects}) )(ProjectsSummaryLayout) 

and I get:

Warning: Stateless function components cannot be given refs (See ref "wrappedInstance" in ProjectsSummaryLayout created by Connect(ProjectsSummaryLayout)). Attempts to access this ref will fail.

What is it trying to tell me? Am I actually doing something wrong?

I see discussion about this here but unfortunately I simply don't understand the conclusion.

like image 551
GreenAsJade Avatar asked Mar 12 '16 01:03

GreenAsJade


People also ask

What is a stateless function?

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.

Can stateless components have functions?

A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.

Why functional components are called stateless?

Functional Component or Stateless Component: 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.


1 Answers

In React, refs may not be attached to a stateless component.

React Redux 3 attaches a ref to the component you give it regardless of whether or not it's stateless. The warning you see comes from React because internally, React Redux 3 attaches a ref to the stateless component you supplied (ProjectsSummaryLayout).

You're not doing anything wrong and according to this GitHub comment, you can safely ignore the warning.

In React Redux 4, no ref is attached to the wrapped component by default, which means if you upgrade to React Redux 4, the warning should go away.

like image 124
Alex Booker Avatar answered Oct 02 '22 05:10

Alex Booker