React Component: Handling null props

Sometimes React does not render when we expect it to, one possible reason is because it cannot process the value null.

Here is our predefined code, we will only be concerned with currentVideo.

import React, {Component} from 'React';
const VideoDisplay = ({currentVideo}) => {
return (
// render video with iframe using currentVideo
);
};
class App extends React.Component = {
  constructor(props) {
super(props);
this.state = {
videos: [],
currentVideo: null
}
}
  componentWillMount() {
// fires up an ajax that gets videos from youtube
// and sets the state with this.setState
}
  render() {
return (
<div>
<VideoDisplay currentVideo = {this.state.currentVideo} />
</div>
)
}
};

This code will break because React wants to render immediately. The parent component cannot fetch information fast enough to satisfy the needs of the child component. The VideoDisplay component will try to render before the ajax request in App is made. So what we need to do now is to add a conditional check to see if the currentVideo is null. If currentVideo is null, then we want to return some filler JSX.

const VideoDisplay = ({currentVideo}) => {
if (!currentVideo) { // evaluates to true if currentVideo is null
return <div>Loading...</div>;
}
return (
// render currentVideo using iframe
);
};

The loading div will appear for a very brief moment before the youtube data overtakes the App state.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.