I am trying to display some text in React JS frontend in place of a profile image when it isn't available.Basically, I pass the current customer name to a function which extracts the first characters of all the words in the name. I am able to display just the name but when I do a function call, I get Cannot read property 'match' of undefined" error and the page does not render. Console.log() displays undefined.
HTML:
<li className="nav-item">
<div id="container_acronym">
<div id="name_acronym">
{this.acronym_name(this.state.lead_details.customer_name)}
</div>
</div>
</li>
JS:
acronym_name(str){
var regular_ex=/\b(\w)/g;
var matches = str.match(regular_ex);
var acronym = matches.join('');
document.getElementById("name_acronym").innerHTML = acronym;
}
this.state.lead_details.customer_name
seems undefined, so you need to catch that case.You have multiple ways of doing this, if you use babel this declaration with default value should work:
Otherwise you can also check inside the function if undefined was given:
Lastly you could in some way prevent giving undefined to the function in the first place. For example like this: