forwardref react code example
Example 1: react forwardref
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Example 2: React Children map example
export default class SomeComponent extends React.Component {
render() {
const childrenWithWrapperDiv = React.Children.map(this.props.children, child => {
return (
<div className="some-component-special-class">{child}</div>
);
});
return (
<div className="some-component">
<p>This component has {React.Children.count(this.props.children)} children.</p>
{childrenWithWrapperDiv}
</div>
);
}
}
Example 3: Did you mean to use React.forwardRef()?
import {useRef} from 'react';
const inputRef = useRef(null);
<section ref={inputRef} >...</section>