idev0085 / react-boilerplate

0 stars 0 forks source link

What are forward refs? #34

Open idev0085 opened 3 years ago

idev0085 commented 3 years ago

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

import React from "react";
import ChildRef from "./child";
class Refs extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }
    componentDidMount() {
        this.myRef.current.focus();
    }

    render() {
        return (
            <div className="center">
                <ChildRef ref={this.myRef} />
            </div>
        );
    }
}
export default Refs;

import React from "react";
import "./style.css"
class ChildRef extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        console.log(this.props)
        return (
            <input type="text" ref={this.props.forwardRef} />
        );
    }
}
export default React.forwardRef((props, ref) => <ChildRef {...props} forwardRef={ref} />)