From the React docs (my italics):
Refs may not be attached to a stateless function, because the component does not have a backing instance. You can always wrap a stateless component in a standard composite component and attach a ref to the composite component.
And the 0.14 changelog (my italics):
Since no component instance is created for a functional component, any ref added to one will evaluate to null. Functional components do not have lifecycle methods, but you can set .propTypes and .defaultProps as properties on the function.
In lecture 21 of Dan Abramov's Redux egghead tutorials, we write the following stateless functional component for adding a todo:
const AddTodo = ({
onAddClick,
}) => {
let input;
return <div>
<input ref = {node => {
input = node;
}} />
<button onClick = {() => {
onAddClick(input.value)
input.value='';
}}>Add Todo</button>
</div>
}
This actually works when put in to the composite component of the app and ref did not return null as promised by the React docs!
Implementation of AddTodo in the composite component looks like this:
class TodoApp extends Component {
render() {
//console.log(store.getState());
log();
const {
todos,
visibilityFilter,
} = this.props;
const visibleTodos = getVisibleTodos(
todos,
visibilityFilter
);
return (
<div>
<AddTodo onAddClick = {
(input) => {
store.dispatch({
type:'ADD_TODO',
text: input,
id: nextTodoId++,
})
}
}/>
The docs do say that we can wrap the stateless component in a composite component and attach a ref to the composite component. The key here being the attachment to the composite component, but my ref is still attached to the stateless AddTodo in my implementation.
My questions are:
AddTodohere really is a stateless functional component, is that not right?If not, why not? (It definitely looks like one but I may be missing the salient features of what it means to be stateless)
If yes to question 1, then how is the behavior of being able to use a
refhere consistent with what's being presented in the React docs?