olo
olo

Reputation: 5271

react component class variable access

How do I access this the_frame variable?

export default class oneApp extends React.Component {
    constructor (props) {
        super(props);
        const the_frame = document.getElementsByClassName("frame")[0];
    }

    oneFunc() {  
        the_frame.style.display = "none"; // How do I access the_frame ?
    }

    twoFunc() {
        the_frame.style.display = "block"; 
    }

    render() {
        return (
            <div className="frame">Hello World</div>
        )
    }
}

I also tried this.the_frame = document.getElementsByClassName("frame")[0]; but can't access the_frame. Thanks

Upvotes: 2

Views: 1779

Answers (2)

pethel
pethel

Reputation: 5537

In react you need to use refs. React manages the rendering so you have no guarantee that your element i accessible the moment you are trying to reach it. It in the constructor so your render haven run yet.

More reading https://facebook.github.io/react/docs/refs-and-the-dom.html

Upvotes: 2

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

You should use the ref attribute if you would like a reference to the DOM element.

https://facebook.github.io/react/docs/refs-and-the-dom.html

Upvotes: 2

Related Questions