I
I
IIITRIX2019-06-08 15:54:43
React
IIITRIX, 2019-06-08 15:54:43

How to fix 'toUpperCase' of undefined?

export class Avatar extends React.Component {
  render(){
    let {name, size, radius, className} = this.props
    let char = name.trim()[0].toUpperCase()
    let bgColor
    if ( /[А-Я]/.test(char) ) {
      let index = char.charCodeAt() - 1040
      bgColor = russian[index]
    } else if ( /[A-Z]/.test(char) ) {
      let index = char.charCodeAt() - 65
      bgColor = english[index]
    } else if( /[\d]/.test(char) ) {
      bgColor = russian[parseInt(char)]
    } else {
      bgColor = [0,0,0]
    }
    let style = {
      backgroundColor: `rgb(${bgColor})`,
      width: size,
      height: size,
      font: Math.floor(size/2) + 'px/100px Helvetica, Arial, sans-serif',
      lineHeight: (size + Math.floor(size/20)) + 'px',
      color: "aliceblue",
      textAlign: 'center',
      borderRadius: radius
    }
    return(
      <div className={className} style={ style }>
        {char}
      </div>
    )
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2019-06-08
@IIITRIX

let char = name&&name.trim()[0]?name.trim()[0].toUpperCase():null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question