How to use React.forwardRef in a class based component? - javascript

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 to always use the same prop for the ref can be achieved by proxying class export 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}
/>);
So basically, we are forced to have a different prop to forward ref, but it can be done under the hub. It's important that the public use it as a normal ref.

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 need to use a different prop name to forward the ref to a class. innerRef is commonly used in many libraries.

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.

This can be accomplished with a higher-order component, if you like:
import React, { forwardRef } from 'react'
const withForwardedRef = Comp => {
const handle = (props, ref) =>
<Comp {...props} forwardedRef={ref} />
const name = Comp.displayName || Comp.name
handle.displayName = `withForwardedRef(${name})`
return forwardRef(handle)
}
export default withForwardedRef
And then in your component file:
class Boop extends React.Component {
render() {
const { forwardedRef } = this.props
return (
<div ref={forwardedRef} />
)
}
}
export default withForwardedRef(Boop)
I did the work upfront with tests & published a package for this, react-with-forwarded-ref: https://www.npmjs.com/package/react-with-forwarded-ref

Incase you need to reuse this in many difference components, you can export this ability to something like withForwardingRef
const withForwardingRef = <Props extends {[_: string]: any}>(BaseComponent: React.ReactType<Props>) =>
React.forwardRef((props, ref) => <BaseComponent {...props} forwardedRef={ref} />);
export default withForwardingRef;
usage:
const Comp = ({forwardedRef}) => (
<input ref={forwardedRef} />
)
const EnhanceComponent = withForwardingRef<Props>(Comp); // Now Comp has a prop called forwardedRef

In case anyone is still having trouble combining React.forwardRef() with a HOC like react-redux connect() then this is how I got it to work:
export default connect(mapStateToProps, mapDispatchToProps)(
React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)
);

Related

How to get HOC in react to override props?

My props on an HOC do not seem to be overriding. I feel as though it might be the notation I'm using. Here is what I have right now.
export const HOCComponent = ({ someProp }) => (
<ContainerComponent
propOne={someValueOne}
propTwo={someValueTwo}
propThree={someValueThree)
/>
);
export const wrapperComponent = props =>(
<HOCComponent {...props} propThree={someValueFour}/>
);
someValueFour does not seem to override someValueThree. Any suggestions would be super helpful! Thank you.
Swap the order of the passed props such that anything you pass later overrides anything passed previously.
export const wrapperComponent = props =>(
<HOCComponent propThree={someValueFour} {...props} />
);
The HOCComponent wrapper component needs to also pass along all props to the component it's wrapping.
export const HOCComponent = (props) => (
<ContainerComponent
propOne={someValueOne}
propTwo={someValueTwo}
propThree={someValueThree}
{...props}
/>
);
Just a minor point about terminology, nothing in your code snippet is a Higher Order Component. HOCs consume a React component and return a new React Component.
An Example:
const withMyHOC = WrappedComponent => props => {
// any HOC logic
return (
<Wrapper
// <-- any wrapper props
>
<WrappedComponent
{...props} // <-- pass props through
// <-- override any props
/>
</Wrapper>
);
};
usage:
export default withMyHOC(SomeComponent);
I saw you don't pass props from HOCComponent to ContainerComponent so propThree is not override. You need to pass someProp to ContainerComponent:
<ContainerComponent propOne propTwo propThree {...someProp} />

Inherit prop-types when a component was rendered through props

Is there a way to inherit prop-types, when a component was rendered through parents prop? Assuming, we don't have access directly to 'ChildProps' and 'Props' interface?
Parent component
interface ChildProps {
counter: number;
setCounter: React.Dispatch<React.SetStateAction<number>>;
}
interface Props {
child: React.ElementType<ChildProps>;
}
function Parent({ child: Child }: Props) {
const [counter, setCounter] = React.useState(0);
return (
<div>
<Child counter={ counter } setCounter={ setCounter } />
</div>
);
}
Child component
function Child(props) {
return (
<div>
// 'counter' is missing in props validation eslint(react/prop-types)
<p>{ props.counter }</p>
// 'setCounter' is missing in props validation eslint(react/prop-types)
<button onClick={ () => props.setCounter(props.counter + 1) }>
inc
</button>
</div>
);
}
Jack,
In React, you shouldn't really extend / inherit from classes other than React.Component, it's the only convention we follow in React to write components.
Functional composition is how we do abstractions with, like: writing a HOC to give certain kind of methods or properties to anyother component.
const withAdditionalProps = (someProps) => WrappedComponent => (
class NewWrappedComponent extends React.Component {
givenMethod = () => { /* some algorithm */ }
render(){
const newProps = { ...this.props, givenMethod: this.givenMethod }
return (
<WrappedComponent {...newProps}>
{this.props.children}
</WrappedComponent>
);
};
}
);
I hope that, or some of it make sense.

How to access a public method from a wrapped Component using TypeScript?

I am working on a React project using TypeScript. They wrapped the react-select component into another component. The wrapped component is the following:
import * as React from "react";
import Select from "react-select";
import { Props as SelectProps } from "react-select/lib/Select";
export interface SelectValue {
label: string;
value: string;
}
export interface SelectFieldProps<TValue> extends SelectProps<TValue> {
label?: string;
}
type GenericSelectField<TValue> = React.StatelessComponent<
SelectFieldProps<TValue>
>;
const SelectField: GenericSelectField<SelectValue> = ({
label = "",
...rest
}) => (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select classNamePrefix="react-select" {...rest} />
</div>
);
export default SelectField;
I would like to access the method blur from react-select:
React-select exposes two public methods:
...
blur() - blur the control programatically
But, I don't know how to expose it in my Component, so I could invoke it. Any ideas?
You can use ref property on the Select component to get a reference to the instance of this component.
Then you can call the blur method of this instance.
const SelectField: GenericSelectField<SelectValue> = ({label = "",...rest}) => {
const selectEl = React.useRef(null);
// this function could be a callback
function handleBlur() {
selectEl.current.blur();
}
return (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select ref={selectEl} classNamePrefix="react-select" {...rest} />
</div>
);
}
export default SelectField;
If you need to access the blur method outside of your SelectField component, you could use forwardRef to reference Select instead of the SelectField.
const SelectField = (props, ref) => {
const {label = "",...rest} = props;
const selectEl = React.useRef(null);
return (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select ref={ref} classNamePrefix="react-select" {...rest} />
</div>
);
}
export default React.forwardRef(SelectField);
Then you can call the blur method with the reference of the SelectField component :
const ref = React.createRef();
<SelectField ref={ref} label=""/>;
ref.blur();
If I understand this correctly you want to trigger Select's blur() inside of SelectField.
There are many ways for example parent-child-binding it via props.
Here is a discussion about this:
Call child method from parent
If you want to access it from outside the SelectField component, I would recommend using React.forwardRef to forward the ref prop to your SelectField component so you can assign it on your own:
/* ... */
type GenericSelectField<TValue> = React.StatelessComponent<
SelectFieldProps<TValue>
>;
type SelectFieldWithRef<TValue> = React.StatelessComponent<
SelectFieldProps<TValue>,
React.Ref<*>
>;
const RefSelectField: SelectFieldWithRef<SelectValue> = (props, ref: any) => {
/* ... */
return (<Select ref={ref} {...} />);
};
const SelectField: GenericSelectField<SelectValue> = React.forwardRef(RefSelectField);
export default SelectField;
In the component you want to call blur you have to do the following:
class ParentComponent extends Component {
constructor(props) {
super(props);
this.selectRef = React.createRef();
}
somehowTriggerBlur = () => this.selectRef.current.blur();
render() {
return (<SelectField ref={ref} {...} />);
}
}

React/ES6: curly braces in function signature? [duplicate]

I know you can pass all a react components props to it's child component like this:
const ParentComponent = () => (
<div>
<h1>Parent Component</h1>
<ChildComponent {...this.props} />
</div>
)
But how do you then retrieve those props if the child component is stateless? I know if it is a class component you can just access them as this.prop.whatever, but what do you pass as the argument into the stateless component?
const ChildComponent = ({ *what goes here?* }) => (
<div>
<h1>Child Component</h1>
</div>
)
When you write
const ChildComponent = ({ someProp }) => (
<div>
<h1>Child Component {someProp}</h1>
</div>
)
From all the props that you are passing to the childComponent you are just destructuring to get only someProp. If the number of props that you want to use in ChildComponents are countable(few) amongst the total number of props that are available, destructuring is a good option as it provides better readability.
Suppose you want to access all the props in the child component then you need not use {} around the argument and then you can use it like props.someProp
const ChildComponent = (props) => (
<div>
<h1>Child Component {props.someProp}</h1>
</div>
)
Are you looking for the ES6 named argument syntax (which is merely destructuring) ?
const ChildComponent = ({ propName }) => (
<div>
<h1>Child Component</h1>
</div>
)
const ChildComponent = (props) => ( // without named arguments
<div>
<h1>Child Component</h1>
</div>
)
Optionally there is a second argument to your function depending of whether you specified a context for your component or not.
Perhaps it would be more helpful wityh a links to the docs. As stated in the first article about functional components. Whatever props passed on to the component is represented as an object passed as first argument to your functional component.
To go a little further, about the spread notation within jsx.
When you write in a component :
<Child prop1={value1} prop2={value2} />
What your component will receive is an plain object which looks like this :
{ prop1: value1, prop2: value2 }
(Note that it's not a Map, but an object with only strings as keys).
So when you're using the spread syntax with a JS object it is effectively a shortcut to this
const object = { key1: value1, key2: value2 }
<Component {...object}/>
Is equivalent to
<Component key1={value1} key2={value2} />
And actually compiles to
return React.createElement(Component, object); // second arg is props
And you can of course have the second syntax, but be careful of the order. The more specific syntax (prop=value) must come last : the more specific instruction comes last.
If you do :
<Component key={value} {...props} />
It compiles to
React.createElement(Component, _extends({ key: value }, props));
If you do (what you probably should)
<Component {...props} key={value} />
It compiles to
React.createElement(Component, _extends(props, { key: value }));
Where extends is *Object.assign (or a polyfill if not present).
To go further I would really recommend taking some time to observe the output of Babel with their online editor. This is very interesting to understand how jsx works, and more generally how you can implement es6 syntax with ES5 tools.
const ParentComponent = (props) => (
<div>
<h1>Parent Component</h1>
<ChildComponent {...props} />
</div>
);
const ChildComponent = ({prop1, ...rest}) =>{
<div>
<h1>Child Component with prop1={prop1}</h1>
<GrandChildComponent {...rest} />
</div>
}
const GrandChildComponent = ({prop2, prop3})=> {
<div>
<h1>Grand Child Component with prop2={prop1} and prop3={prop3}</h1>
</div>
}
You can use Spread Attributes reducing code bloat. This comes in the form of {'somearg':123, ...props} or {...this.props}, with the former allowing you to set some fields, while the latter is a complete copy. Here's an example with ParentClass.js :
import React from 'react';
import SomeComponent from '../components/SomeComponent.js';
export default class ParentClass extends React.Component {
render() {
<SomeComponent
{...this.props}
/>
}
}
If I do, <ParentClass getCallBackFunc={() => this.getCallBackFunc()} />, or if I do <ParentClass date={todaysdatevar} />, the props getCallBackFunc or date will be available to the SomeComponent class. This saves me an incredible amount of typing and/or copying/pasting.
Source: ReactJS.org: JSX In Depth, Specifying the React Element Type, Spread Attributes. Official POD:
If you already have props as an object, and you want to pass it in JSX, you can use ... as a “spread” operator to pass the whole props object. These two components are equivalent:
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}```
Now, let's apply this to your code sample!
const ParentComponent = (props) => (
<div>
<h1>Parent Component</h1>
<ChildComponent {...props} />
</div>
);
I thought I would add a simple ES2015, destructuring syntax I use to pass all props from a functional parent to a functional child component.
const ParentComponent = (props) => (
<div>
<ChildComponent {...props}/>
</div>
);
Or if I have multiple objects (props of parent, plus anything else), I want passed to the child as props:
const ParentComponent = ({...props, ...objectToBeAddedToChildAsProps}) => (
<div>
<ChildComponent {...props}/>
</div>
);
This destructuring syntax is similar to the above answers, but it is how I pass props along from functional components, and I think it is really clean. I hope it helps!
But how do you then retrieve those props if the child component is stateless?
const ChildComponent = ({ *what goes here?* }) => (
<div>
<h1>Child Component</h1>
</div>
)
ChildComponent holds the name and the props will be the argument in the arrow function syntax just as you need:
const ChildComponent = props => (
<div>
<p>{props.value ? props.value : "No value."}</p>
</div>
);
If you Babel-it it will create something like this:
var ChildComponent = function ChildComponent(props) {
return React.createElement(
"div",
null,
React.createElement(
"p",
null,
props.value ? props.value : "No value."
)
);
};
For some reason, what seems to work for me is a variation on Shubham's answer above:
const ChildComponent = props => (
<div>
<h1>Child Component {props[0].someProp}</h1>
</div>
)
Using this
const ParentComponent = ({ prop1, prop2, prop3 }) => (
<div>
<h1>Parent Component</h1>
<ChildComponent {...{ prop1, prop2, prop3 }} />
</div>
);
const ChildComponent = ({ prop1, prop2, prop3 }) =>{
<div>
<h1>Child Component with prop1={prop1}</h1>
<h1>Child Component with prop2={prop2}</h1>
<h1>Child Component with prop2={prop3}</h1>
</div>
}

How can I use 'this' in defaultProps React.Component class syntax?

In the past I was able to set a default prop that used this like so...
let MyButton = React.createClass({
getDefaultProps() {
return {
buttonRef: (ref) => this.button = ref
};
},
But now that I'm using JS classes MyButton looks like this...
class MyButton extends React.Component {
static defaultProps = {
buttonRef: (ref) => this.button = ref
};
And I get an error saying that this is undefined.
What do I need to do to be able to set default props that use this?
EDIT: Add some context
Setting a default buttonRef prop allowed me to use the ref in the MyButton component but also always be able to pass in a custom ref if a parent component needs to access the MyButton DOM node.
class MyButton extends React.Component {
static defaultProps = {
buttonRef: (ref) => this.button = ref
};
componentDidMount() {
Ladda.bind(this.button);
}
render() {
return (
<button
ref={(ref) => this.button = this.props.buttonRef(ref)}
onClick={this.props.handleClick}
>
{this.props.buttonText}
</button>
);
}
}
So then my button can always get hooked in to Ladda: Ladda.bind(this.button)
And if I need to access that button's DOM node in a parent component I can do so by passing in buttonRef as a prop like...
class MouseOverButton extends React.Component {
componentDidMount() {
this.mouseEnterButton.addEventListener("mouseover", doSomething(event));
}
render() {
return (
<div>
<MyButton
buttonRef={(ref) => this.mouseEnterButton = ref}
/>
</div>
);
}
}
EDIT: Apparently my simplified example doesn't illustrate the point well enough so I can come up with a more practical example or y'all can just answer the original question: What do I need to do to be able to use this in my defaultProps? Can I no longer do that using JS class syntax?
Where this convention of having a defaultProp for a specific element's ref has been useful is when using a HOC that hooks a nested component into some 3rd party API. I have an AddressSearch HOC that takes a node via a function passed to the wrapped component. Then it uses that node to hook it up with Google's Places API.
So I've got my addAddressSearch(component) function from my HOC. It adds the functions needed to hook up the Google places API. But for Google's API to work I need to know what DOM node I'm working with. So I pass my Input component an inputRef that gives my AddressSearchInput access to the appropriate node.
class AddressSearchInput extends React.Component {
static defaultProps = {
inputRef: (ref) => this.addressSearchInput = ref
};
componentDidMount() {
let node = this.addressSearchInput;
this.props.mountAddressSearch(node);
}
render() {
return (
<div>
<Input
inputAttributes={inputAttributes}
inputRef={(ref) => this.addressSearchInput = this.props.inputRef(ref)}
labelText={<span>Event address or venue name</span>}
labelClassName={labelClassName}
/>
</div>
);
}
}
AddressSearchInput = addAddressSearch(AddressSearchInput);
module.exports = AddressSearchInput;
// Here's the Input component if that helps complete the picture here
class Input extends React.Component {
render() {
return (
<div>
<Label>{this.props.labelText}</Label>
<HelperText text={this.props.inputHelperText} />
<input
{...this.props.inputAttributes}
ref={this.props.inputRef}
></input>
</div>
);
}
}
So now when I want to use my AddressSearchInput in a parent component that needs to add an eventListener to the relevant node I can just pass AddressSearchInput an inputRef prop.
class VenueStreetAddress extends React.Component {
componentDidMount() {
let node = this.venueStreetAddressInput;
this.props.mountValidateOnBlur(node, venueValidationsArray);
},
render() {
return (
<div>
<AddressSearchInput
inputRef={(ref) => this.venueStreetAddressInput = ref}
hasError={this.props.hasError}
/>
{this.props.errorMessageComponent}
</div>
);
}
}
And I can use AddressSearchInput all over the place and it doesn't break anything.
class UserStreetAddress extends React.Component {
componentDidMount() {
let node = this.userStreetAddressInput;
this.props.mountValidateOnBlur(node, userValidationsArray);
},
render() {
return (
<div>
<AddressSearchInput
inputRef={(ref) => this.userStreetAddressInput = ref}
hasError={this.props.hasError}
/>
{this.props.errorMessageComponent}
</div>
);
}
}
Maybe this way is convoluted and wrong but I don't have the time to figure out another way to do it on my own. So either point me to a tutorial(s) on the best way to hook into 3rd party APIs and add dynamic form validation without using refs or answer my original question which is...
What do I need to do to be able to use this in my defaultProps? Can I no longer do that using JS class syntax?
EDIT: In attempting to explain my use case I had the idea to make my defaultProps look like this...
static defaultProps = {
inputRef: (ref) => ref
};
which seems to be working without error.
In any case, the original question still stands. What do I need to do to be able to use this in my defaultProps? Can I no longer do that using JS class syntax?
This really should be a method, not a property.
class MyButton extends React.Component {
setButtonRef (ref) {
this.button = ref;
}
componentDidMount() {
Ladda.bind(this.button);
}
render() {
return (
<button
ref={ ref => this.setButtonRef(ref) }
onClick={this.props.handleClick}
>
{this.props.buttonText}
</button>
);
}
}
If you want a ref to the button, bind a variable at the class level and assign it to that class variable. Example:
export default class MyComponent extends Component {
componentDidMount() {
// button will be available as `this.button`
}
button = null; // initialize to null
render() {
return (
<div>
<Button ref={e => { this.button = e; }} />
</div>
);
}
}
Since a static property has no knowledge of class instances, if it's strictly necessary to make a static method aware of a given instance, the only way would be to pass to the static method the instance as an argument:
<button
ref={(ref) => this.button = this.props.buttonRef(this, ref)}
onClick={this.props.handleClick}
>
And in your defaultProp, use the instance:
static defaultProps = {
buttonRef: (instance, ref) => instance.button = ref
};

Categories

Resources