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 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?
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM