30
loading...
This website collects cookies to deliver better user experience
AwesomeButton
component, that renders the native button DOM element.functon AwesomeButton(props) {
return(
<button>{props.children}</button>
)
}
AwesomeButton
, will usually not obtain a ref to the inner DOM element. This encapsulation is good, because it prevents components from relying heavily on each other's DOM structure. A high level of encapsulation is desirable on application-level, it can be unpractical for highly reusable leaf components (think of the React tree). These leaf components like AwesomeButton
are used like native DOM elements, like a button, and managing focus, selection or animations require access to their DOM nodes.AwesomeButton
is forwarded down to the DOM button, which gives components using the AwesomeButton
component access to the button DOM node, just like they would use a DOM button directly.const AwesomeButton = React.forwardRef((props, ref) => (
<button ref={ref}>{props.children}</button>
));
const ref = React.useRef();
<AwesomeButton ref={ref}>Click it</AwesomeButton>;
ref
, ref.current
will point to the <button>
DOM element.function logProps(WrappedComponent) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return LogProps;
}
logProps
HOC passes all props through the wrapped components and, it doesn't affect the rendered output. Let's apply this on the AwesomeButton
.class AwesomeButton extends React.Component {
//...
}
export default logProps(AwesomeButton);
import AwesomeButton from './AwesomeButton';
//...
const ref = createRef();
//...
<AwesomeButton
label="click it"
handleClick={handleClick}
ref={ref}
/>;
ref
is not a prop. The reference passed to AwesomeButton
, which is now a Higher-Order-Component, will not be passed down, because ref is not a prop. Instead, the reference will be attached to the HOC logProps
.AwesomeButton
component using forwardRef
. The React.forwardRef
API receives props
and ref
parameters and returns a React.node
.function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const { forwardedRef, ...rest } = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// The second parameter in forwardRef can be used as a normal prop.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
ref
and key
are handled differently.React.forwardRef
API receives props
and ref
parameters and returns a React.node
.ref
is not a prop and will not be automatically forwarded with other props. React.forwardRef
has to be used.