I'm trying to use React.forwardRef, but tripping over how to get it to work in a class based component (not HOC).
The docs examples use elements and functional components, even wrapping classes in functions for higher order components.
So, starting with something like this in their ref.js file:
const TextInput = React.forwardRef(
(props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);
and instead defining it as something like this:
class TextInput extends React.Component {
render() {
let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
return <input type="text" placeholder="Hello World" ref={ref} />;
}
}
or
class TextInput extends React.Component {
render() {
return (
React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
);
}
}
only working :/
Also, I know I know, ref's aren't the react way. I'm trying to use a third party canvas library, and would like to add some of their tools in separate components, so I need event listeners, so I need lifecycle methods. It may go a different route later, but I want to try this.
The docs say it's possible!
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
from the note in this section.
But then they go on to use HOCs instead of just classes.
The idea of always using the same prop for the ref can be achieved by exporting the proxy class with a helper.
class ElemComponent extends Component { render() { return ( <div ref={this.props.innerRef}> Div has a ref </div> ) } } export default React.forwardRef((props, ref) => <ElemComponent innerRef={ref} {...props} />);Basically we are forced to have a different prop to send the reference, but it can be done below center. It is important that the public uses it as a normal reference.
class BeautifulInput extends React.Component { const { innerRef, ...props } = this.props; render() ( return ( <div style={{backgroundColor: "blue"}}> <input ref={innerRef} {...props} /> </div> ) ) } const BeautifulInputForwardingRef = React.forwardRef((props, ref) => ( <BeautifulInput {...props} innerRef={ref}/> )); const App = () => ( <BeautifulInputForwardingRef ref={ref => ref && ref.focus()} /> ) You must use a different prop name to forward the reference to a class. innerRef is commonly used in many libraries. Right
Basically, this is just a HOC function. If you wanted to use it with class, you can do this by yourself and use regular props.
class TextInput extends React.Component {
render() {
<input ref={this.props.forwardRef} />
}
}
const ref = React.createRef();
<TextInput forwardRef={ref} />
This pattern is used for example in styled-components and it's called innerRef there.