Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'substr' of null - React

I have a code like this in React...

import React, { Component } from 'react';

class Card extends Component {
constructor(props) {
    super(props);
    this.state = {
        eventName: props.eventName,
        eventDate: props.eventDate,
        eventDesc: props.eventDesc,
        eventPic: props.eventPic
    }
}

render () {

    const { eventDate, eventDesc, eventName, eventPic } = this.state;
    return (
        <article className="br2 ba dark-gray b--black-10 dib ma3 mw5 shadow-hover">
            <img src={eventPic} className="db w-100 br2 br--top" alt={eventName} />
            <div className="pa2 ph3-ns pb3-ns">
                <div className="dt w-100 mt1">
                    <div className="dtc">
                        <h1 className="f5 f4-ns mv0">{eventName}</h1>
                    </div>
                    <div className="dtc tr">
                        <h2 className="f5 mv0">{eventDate}</h2>
                    </div>
                </div>
                <p className="f6 lh-copy measure mt2 mid-gray">
                    {eventDesc.substr(0, 140)}
                </p>
            </div>
        </article>
    )
}
}

export default Card;

The Problem I have is in this block code

{eventDesc.substr(0, 140)} // This is meant to limit the eventDescription's chars.

it gives me a TypeError: Cannot read property 'substr' of null.

Can you please help me how to overcome this error? Thank you

like image 787
Ricardo Sawir Avatar asked Jun 21 '26 19:06

Ricardo Sawir


1 Answers

basically you are assigning a value to eventDesc with a default value of props.eventDesc. but if you are not passing that value(should be undefined) OR you are passing a null value you will get that behaviour.

you can add a default value on your render to solve this:

const { eventDate ="", eventDesc = "", eventName = "", eventPic = "" } = this.state;

but the best should be to have a default value ON the constructor so you do it only once:

constructor(props) {
    super(props);
    this.state = {
        eventName: props.eventName || "",
        eventDate: props.eventDate || "",
        eventDesc: props.eventDesc || "",
        eventPic: props.eventPic || ""
    }
}
like image 166
Prince Hernandez Avatar answered Jun 23 '26 09:06

Prince Hernandez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!