Alex Yong
Alex Yong

Reputation: 7645

cannot read property of null using state in react

I found below code make sense, it simply show the filename when user uploaded a file but I got error of cannot read property of undefined of filename? why? isn't I already set filename to null in the first place?

export default class fileUpload extends Component {
    constructor(props) {
        super(props);

        React.defaultProps = {
            filename: null
        }
    }

    handleOnChange = (e) => {
        this.setState({filename: e.target.files[0].name})
    }

    render() {
        return(
            <div>
                <input type="file" onChange={this.handleOnChange}/>
                {this.state.filename && <span className="filename-placeholder">{this.state.filename}</span>}
            </div>
        )
    }
}

Upvotes: 2

Views: 1880

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Include this line, it will work:

constructor(props) {
    super(props);
    this.state = {};   //line
    React.defaultProps = {
        filename: null
    }
}

You need to define the state in constructor.

Few Suggestions:

1. defaultProps is used to set the default value of props, not the default value of state variable. defaultProps is not required here, because you are using the state variable. Check the example.

2. You define the class name as fileUpload (started with lowercase letter), instead of that use FileUpload (started with uppercase letter.)

Check the working example:

class FileUpload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           filename: null
        }
    }

    handleOnChange = (e) => {
        this.setState({filename: e.target.files[0].name})
    }

    render() {
        return(
            <div>
                <input type="file" onChange={this.handleOnChange}/>
                {this.state.filename && <span className="filename-placeholder">{this.state.filename}</span>}
            </div>
        )
    }
}

ReactDOM.render(<FileUpload/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Upvotes: 3

Related Questions