aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/jazzicon/jazzicon.component.js
blob: fcb1c59b196d92f7f52c4eb7ef878555832695c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import isNode from 'detect-node'
import { findDOMNode } from 'react-dom'
import jazzicon from 'jazzicon'
import iconFactoryGenerator from '../../../lib/icon-factory'
const iconFactory = iconFactoryGenerator(jazzicon)

/**
 * Wrapper around the jazzicon library to return a React component, as the library returns an
 * HTMLDivElement which needs to be appended.
 */
export default class Jazzicon extends PureComponent {
  static propTypes = {
    address: PropTypes.string.isRequired,
    className: PropTypes.string,
    diameter: PropTypes.number,
    style: PropTypes.object,
  }

  static defaultProps = {
    diameter: 46,
  }

  componentDidMount () {
    if (!isNode) {
      this.appendJazzicon()
    }
  }

  componentDidUpdate (prevProps) {
    const { address: prevAddress } = prevProps
    const { address } = this.props

    if (!isNode && address !== prevAddress) {
      this.removeExistingChildren()
      this.appendJazzicon()
    }
  }

  removeExistingChildren () {
    // eslint-disable-next-line react/no-find-dom-node
    const container = findDOMNode(this)
    const { children } = container

    for (let i = 0; i < children.length; i++) {
      container.removeChild(children[i])
    }
  }

  appendJazzicon () {
    // eslint-disable-next-line react/no-find-dom-node
    const container = findDOMNode(this)
    const { address, diameter } = this.props
    const image = iconFactory.iconForAddress(address, diameter)
    container.appendChild(image)
  }

  render () {
    const { className, style } = this.props

    return (
      <div
        className={className}
        style={style}
      />
    )
  }
}