Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand web TextInput as the user types #284

Merged
merged 4 commits into from
Aug 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions src/components/TextInputFocusable/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import {TextInput} from 'react-native';
* On web we like to have the Text Input field always focused so the user can easily type a new chat
*/
class TextInputFocusable extends React.Component {
constructor(props) {
super(props);

this.state = {
numberOfLines: 1,
};
this.updateNumberOfLines = this.updateNumberOfLines.bind(this);
}

componentDidMount() {
this.focusInput();
}
Expand All @@ -13,13 +22,44 @@ class TextInputFocusable extends React.Component {
this.focusInput();
}

/**
* Check the current scrollHeight of the textarea (minus any padding) and
* divide by line height to get the total number of rows for the textarea.
*
* @param {object} event
*/
updateNumberOfLines(event) {
const target = event.nativeEvent.target;
const computedStyle = window.getComputedStyle(target);
const lineHeight = parseInt(computedStyle.lineHeight, 10) || 20;
const paddingTopAndBottom = parseInt(computedStyle.paddingBottom, 10)
+ parseInt(computedStyle.paddingTop, 10);

// We have to reset the rows back to the minimum before updating so that the scrollHeight is not
// affected by the previous row setting. If we don't, rows will be added but not removed on backspace/delete.
this.setState({numberOfLines: 1}, () => {
this.setState({
numberOfLines: Math.ceil((target.scrollHeight - paddingTopAndBottom) / lineHeight)
});
});
}

focusInput() {
this.textInput.focus();
}

render() {
// eslint-disable-next-line react/jsx-props-no-spreading
return <TextInput ref={el => this.textInput = el} {...this.props} />;
return (
<TextInput
ref={el => this.textInput = el}
onChange={(event) => {
this.updateNumberOfLines(event);
}}
numberOfLines={this.state.numberOfLines}
/* eslint-disable-next-line react/jsx-props-no-spreading */
{...this.props}
/>
);
}
}

Expand Down