React.createRef() does not work - Function components cannot be given refs

1.7k views Asked by At

I have this parent class component

class TransferHolder extends Component {

    constructor(props) {
        super(props);
        this.transfer = React.createRef();
    }

    render() {
        return (
            <div>
                <h1>HELLO !</h1>
                <Transfer ref={this.transfer}/>
                <Button onClick={() => {
                    const TransferRef = this.transfer.current;
                    console.log('Selected: ',
                        TransferRef.state.projectForm.users.right)
                }}>
                    Print
                </Button>
            </div>

        )
    }

}

const mapStateToProps = state => {
    return {
        
    };
};

const mapDispatchToProps = dispatch => {
    return {
        
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(TransferHolder);

When I visit the page an error is shown automatically that says:

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `TransferHolder`.
    in ConnectFunction (at TransferHolder.js:19)
    in div (at TransferHolder.js:17)
    in TransferHolder (created by ConnectFunction)
    in ConnectFunction (created by Context.Consumer)
    in Content (at ContentRoute.js:23)

I just want to access the state of the <Transfer> Component which is a class based Component. However it is also wrapped in redux connect() so I don't know if that does convert it to a functional one.

1

There are 1 answers

3
Peter Lehnhardt On

Let's say the code for your component Transfer looks like this:

const Transfer = props => <p {...props}>Some Transfer component</p>;

If you use this component like above as

<Transfer ref={this.transfer} />

it will fail with the mentioned error message

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

because normal function components can not handle refs by default. To avoid that error, you have to wrap your component in forwardRef:

const Transfer = forwardRef((props, ref) => <p {...props} ref={ref}>Some Transfer component</p>;