简体   繁体   中英

Conditional loading in React.js

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 aa 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?

When doing server side rendering of your React components, you need to do your window check from within the life cycle method componentDidMount , 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.

There are better ways to do it, but if that's the case i would do something like this:

class Hello extends React.Component {

    constructor(props) {
        super(props);
        this.mobile = false;
    }

    componentWillMount(){
        this.mobile = window.innerWidth <= 640
    }

    render() {
        if (this.mobile){
            return (
                <div>Hello Mobile</div>
            );
        }
        else {
            return (
                <div>Hello Desktop</div>
            );
        }
    }
};

ReactDOM.render(
  <Hello/>,
  document.getElementById('app')
);

you can use the operator ternary

return true ? ():()

for example:

render() {
    return this.mobile ? (
    <di> loading </div>
    ):(
    <di> content custom </div>
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM