Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'refs' of null react error react js

Tags:

reactjs

I'm using React js 0.14.3, I'm trying to create a Side Menu component using react but I don't know why I have an "Cannot read property 'refs' of null" when I use the refs like in the react documentation : https://facebook.github.io/react/docs/more-about-refs.html Can you help me please ?

'use strict';

    import React from 'react';
    import BaseComponent from './../../BaseComponent.react';
    import Menu from './SidePanelMenu';
    import MenuItem from './SidePanelMenuItem';

    class SidePanel extends BaseComponent {
        showLeft() {
            this.refs.leftmenu.show();
        }


        render() {
            return(
                <div>
                    <button onClick={this.showLeft}>Show Left Menu!</button>

                    <Menu ref="leftmenu" alignment="left">
                        <MenuItem hash="first-page">First Page</MenuItem>
                        <MenuItem hash="second-page">Second Page</MenuItem>
                        <MenuItem hash="third-page">Third Page</MenuItem>
                    </Menu>
                </div>
            );
        }
    }

    export default SidePanel;
like image 671
fandro Avatar asked Dec 15 '15 20:12

fandro


People also ask

How to fix cannot read property of undefined in React?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

What is ReactDOM createPortal?

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. ReactDOM. createPortal(child, container) The first argument ( child ) is any renderable React child, such as an element, string, or fragment.

What is findDOMNode?

findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated in StrictMode .

Why we use ReactDOM?

What is ReactDOM? ReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page. ReactDOM provides the developers with an API containing the following methods and a few more.


1 Answers

You need to bind context of this.

The line where you are binding your onClick handler:

onClick={this.showLeft}

Needs to be:

onClick={this.showLeft.bind(this)}

Otherwise when you're calling showLeft it can't access this.

like image 77
Kevin Väljaots Avatar answered Sep 22 '22 12:09

Kevin Väljaots