1 | import React from 'react';
|
2 |
|
3 | export default class extends React.Component {
|
4 |
|
5 | constructor (props) {
|
6 | super(props)
|
7 | this.setState({invokeFocus: true});
|
8 | }
|
9 |
|
10 | componentWillReceiveProps (nextProps) {
|
11 | if (nextProps.items.length > this.props.items.length) {
|
12 | this.setState({invokeFocus: true});
|
13 | } else {
|
14 | this.setState({invokeFocus: false});
|
15 | }
|
16 | }
|
17 |
|
18 | componentDidMount () {
|
19 | this.lastInput.focus();
|
20 | }
|
21 |
|
22 | componentDidUpdate () {
|
23 | if (this.state.invokeFocus) {
|
24 | this.lastInput.focus();
|
25 | }
|
26 | }
|
27 |
|
28 | subNote () {
|
29 | if (!this.props.isGift && this.props.showMaySub) return (
|
30 | <div className="email-address__note">
|
31 | This recipient may need to be a subscriber to read this content
|
32 | </div>
|
33 | )
|
34 | }
|
35 |
|
36 | giftNote () {
|
37 | if (this.props.isGift) {
|
38 | const remainder = this.props.credit - this.props.items.length
|
39 | return (
|
40 | <div className="email-address__note">
|
41 | You will have <span className="email-address__gift-count">{remainder} gift article{remainder !== 1 ? 's' : ''}</span> remaining
|
42 | this month
|
43 | </div>
|
44 | )
|
45 | }
|
46 | }
|
47 |
|
48 | inputs () {
|
49 | const maxItems = this.props.isGift ? this.props.credit : 10
|
50 | return this.props.items.map((address, index) => {
|
51 | const error = !this.props.errors[index] ? null : (
|
52 | <div className="email-address__error o-forms-errortext">Please enter a valid email</div>
|
53 | )
|
54 | const lastInput = index + 1 === this.props.items.length;
|
55 | const action = (maxItems === 1 || lastInput && index + 1 < maxItems) ? 'add' : 'remove'
|
56 | const button = (
|
57 | <div className="email-address__button">
|
58 | <button type="button" className="o-buttons o-buttons--big"
|
59 | onClick={() => action === 'add' ? this.props.onAdd() : this.props.onRemove(index)}
|
60 | disabled={maxItems === 1}>
|
61 | <i className={`email-address__button--${action}`}>{action}</i>
|
62 | </button>
|
63 | </div>
|
64 | )
|
65 | return (
|
66 | <div key={index} className={`email-address__item o-forms-group ${error ? 'o-forms--error' : ''}`}>
|
67 | <div className="email-address__input-button">
|
68 | <input type="email" className="o-forms-text email-address__input"
|
69 | ref={(input) => { lastInput ? this.lastInput = input : null; }}
|
70 | value={address}
|
71 | onChange={event => this.props.onItemChange(index, event.target.value)}></input>
|
72 | {button}
|
73 | </div>
|
74 | {error}
|
75 | </div>
|
76 | )
|
77 | })
|
78 | }
|
79 |
|
80 | render () {
|
81 | return (
|
82 | <div className="email-address">
|
83 | <label className="email-address__label">
|
84 | Enter recipient’s email address
|
85 | </label>
|
86 | <div className="email-address__list">
|
87 | {this.inputs()}
|
88 | </div>
|
89 | {this.subNote()}
|
90 | {this.giftNote()}
|
91 | </div>
|
92 | )
|
93 | }
|
94 |
|
95 | }
|