Adding ref with React.cloneElement() fails on class component with functional component error
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
In a class component with all class component children...
constructor(props) {
super(props);
this.myref = React.createRef();
}
render() {
return (
{React.cloneElement(this.props.children[0], {ref: myref})}
);
}
...fails with Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
I get that React.cloneElement() is probably returning a functional wrapper that's confusing React, but given the power of this.props.children, what is the proper way to dynamically add refs? All of the actual children are class components if that matters.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The report names React.cloneElement(), React.createRef(), class components, and functional components, but no repository file or test entry point. Start by reproducing the warning with the shown component structure and determine whether the expected behavior is a React fix or a documentation clarification; done means an agreed, reproducible outcome and a documented or tested resolution.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100