Search code examples
reactjsreact-component

Cannot read property 'length' of null when checking array


I'm trying to show some photos on a website. Everytime I try, I get this error:

Cannot read property 'length' of null

import React, { Component } from 'react';
import axios from 'axios';


class ImagePlayer extends Component {
constructor(props) {
    super(props);
    this.state = {
        photos: null
    };
}

componentDidMount() {
    axios.get(`/api/gameDev/image-files/${this.props.charId}/pics`)
        .then((response) => {
            this.setState({ photos: response.data })
        })
        .catch((error) => {
            console.log(error);
        });

}

showMedia = (props) => {
    return (
        <div>
            {
                props.photos.length > 0 &&
                    <div>
                        {props.photos.map((photo) => photo.title)}
                    </div>
            }
        </div>
    );
}

render() {
    return (
        <div>
            <div>Show Media</div>
            <div>
                {this.showMedia(this.state)}
            </div>
        </div>
    );
}

}

export default ImagePlayer;

I know I did something wrong. If anyone can see anything, please let me know.

Thanks! :)


Solution

  • Set initial photos state to an empty array:

    this.state = {
        photos: []
    };
    

    Alternatively, change props.photos.length > 0 to:

    props.photos && props.photos.length > 0 // or (props.photos || []).length > 0