Ad

Conditional Loading In React.js

- 1 answer

I have the following React Component

const VideoElement = React.createClass({

    render() {
        return (
            <video autoPlay loop muted className="video">
                <source src={this.props.source} type="video/mp4" />
            </video>
        )
    }
});

And I want to have this output just if window.innerWidth <= 640.

My approach was to add an initial state like:

getInitialState() {
     return { isMobile: window.innerWidth <= 640 }
}

And add a a condition in the render() method but if I'm trying to access this.state.isMobile trows me an error with:

window is undefined

Can someone explain me what I'm doing wrong?

It's my approach ok?

Ad

Answer

When doing server side rendering of your React components, you need to do your window check from within the life cycle methodcomponentDidMount, which is only invoked once and only on the client.

When checking things like isMobile on the server side you should try to access what agent string the request came from and pass that information down to your client. Relying on window width in order to hide/show content should be done with CSS instead.

Ad
source: stackoverflow.com
Ad